2016-10-17 121 views
0

我使用Query constuctor在Laravel:如何通過查詢Laravel中的相關表進行搜索?

$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條件查詢構造函數中的相關模型account

回答

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

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(); 
相關問題