如何在查询Laravel中通过相关表进行搜索?

时间:2016-10-17 11:44:29

标签: laravel laravel-5.2 laravel-5.3

我在Laravel中使用Query constuctor:

rdd.saveAsTextFile("alicia.txt")

所以,我尝试过滤构造函数中的行:

 $this->users = User::where(function ($query) 
        use ($request) {

         $query->where('account.email', 'like', '%' . $request->email . '%');

    })->with('account')->get();

但它不起作用,因为模型$query->where('account.email', 'like', '%' . $request->email . '%'); 的连接在下面。

如何通过相关模型account在查询构造函数中使用where条件?

2 个答案:

答案 0 :(得分:1)

whereHas条款来救援。它允许在您的关系上添加查询约束。

$this->users = User::query()
    // Relational query with constraint
    ->whereHas('account', function ($query) use ($request)
    {
        // The query here is scoped to account, 
        // hence you don't need account.email
        $query->where('email', 'like', '%' . $request->email . '%');
    })
    // Still need to eager load 'account' relation
    ->with('account')
    ->get();

答案 1 :(得分:0)

如果要基于相关模型进行查询,则需要使用whereHas('RELATED_MODEL_NAME')

$this->users = User::with('account')->whereHas('account', function($query) use ($request) {
    $query->where('email', 'like', '%' . $request->email . '%');
})->get();

有关详细信息,请查看Querying Relationship Existence