难以捉摸,在人际关系中寻找


Eloquent, search through relationships

通过关系搜索(如WHERE name LIKE %acme%)字段值的正确过程是什么?

假设我们有一个属于CompanyClient模型。现在我想通过$client->company->name字段进行过滤(搜索)。

我试过Client::where('company.name', 'LIKE', 'acme')->get();

但它不起作用。。。

我已经做好了加载准备。。。$includes = array('company')

编辑:忘了提我的关系正在运作。。。

谢谢!

尝试使用热切加载:

$client = Client::with(array('company' => function($query) {
    $query->where('name', 'LIKE', 'acme');
}))->first();

现在我有了更好的理解-Laravel热切加载不使用JOIN查询,这与其他ORM方法不同,据说仍然可以使用Fluent query Builder结构将Eloquent与JOIN一起使用。因此,你将无法通过Eloquent搜索相关模型的价值。使用Fluent接口进行联接:http://laravel.com/docs/database/fluent#joins

您仍然可以通过执行Client::join(。。。。对于这种功能,你应该看看类似于条令的东西。通过

为陡峭的学习曲线做好准备

尝试此

您可以通过在雄辩中使用join方法来实现这一点。

Client::join('companies AS company', 'clients.company_id', '=', 'company.id')
       ->select('clients.*', 'company.name AS company_name')
       ->with('company')
       ->where(function($query) {
           $query->where('company_name', 'LIKE', 'acme');
       })
       ->get();

正如您所看到的,我将companies表加入到客户端,以便在返回数据上有一个company_name。因此,您可以很容易地搜索到公司名称为"acme"的客户。