我有兩個關系表。我使用 where 來過濾記錄,我也使用 wherehas 使用 where 來過濾記錄。但是找不到兩者的區別
uj5u.com熱心網友回復:
如果您使用 where(condition)->with(relation) 查詢將回傳條件匹配的記錄和關系資料(如果有)。如果您使用 where(condition)->whereHas(relation) 查詢將回傳條件匹配且存在關系的記錄
uj5u.com熱心網友回復:
當您將 with() 與 where() 條件一起使用時,您僅在主表而不是相關表上應用條件,但是當您使用 whereHas() 時,這將在關系上應用條件,而不是在主表上應用條件。例如
1) User::with("post")->where('id', 1)->first();
2) User::whereHas("post", function (Builder $query) {
$query->where('status', 1);
})->get();
首先將獲取用戶 ID 為 1 的用戶,而第二個將獲取所有帖子狀態為已發布的用戶
uj5u.com熱心網友回復:
1). 在哪里()
$table::with("relation-name")->where(condition)->get();
簡單地根據此獲取資料,"relation-name"沒有 where(condition)
條件適用于第二個表(關系表);
2). 哪里有()
User::where Has("relation-name", function (Builder $query) {
$query->where('status', 1);
})->get();
wherehas() 在第二個表(關系表)上應用條件;
我的理解,也在我的專案中實踐過這種方式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533695.html
標籤:拉维laravel-5雄辩laravel-4laravel-8
下一篇:受保護的屬性PHPLaravel
