這段代碼:
$users = Users::with(['posts' => function($post) use ($request) {
$post->where('votes', '>', 100);
}])->get();
dd($users->toArray());
像這樣回傳輸出:
0 => [
"user_id" => 1
"posts" => []
]
我該怎么做才能回傳一個空的用戶陣列?我試著這樣做:
$users = Users::with(['posts'])
->where('posts.votes', '>', 100)->get();
dd($users->toArray());
但出現錯誤:
Undefined table: 7 ERROR: issing FROM-clause entry for table "posts"
uj5u.com熱心網友回復:
使用您嘗試過的語法,答案是“否”,因為->with()它不執行任何join邏輯;所以posts那里沒有桌子。
如果要User根據關系條件過濾回傳的記錄,則需要使用has()orwhereHas()方法之一。在您的情況下,由于您正在尋找votes > 100,votes作為一列,因此您需要使用whereHas():
$users = Users::whereHas(['posts' => function($query) {
return $query->where('votes', '>', 100);
}])->get();
這會將User回傳的記錄限制為擁有 100 票或更多票的人。
此外,您可以使用這兩者whereHas()并with()使用相同的功能來過濾和急切加載關系(防止以后運行額外的查詢)。語法為:
$closure = function ($query) {
return $query->where('votes', '>', 100);
});
$users = Users::whereHas(['posts' => $closure]
->with(['posts' => $closure])
->get();
完整的檔案可在此處獲得:
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
uj5u.com熱心網友回復:
我認為你需要使用whereHas方法。你可以這樣試試嗎?
$users = Users::with(['posts'])
->whereHas('posts.votes', function($q){
$q->where('votes', '>', 100);
})->get();
dd(optional($users)->toArray(), $users->toArray());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452477.html
