所以我有一個資料結構如下:
User
id
Collection
user_idgame_id
Game
idstatus
在我的模型中,我有這樣的關系:
User::hasMany(Collection)
Collection::belongsTo(Game)
Game::hasMany(Collection)
所以我要做的是獲取用戶串列并通過集合表包含所有相關游戲。但我只想包括那些具有特定狀態的游戲。我正在使用的代碼(不起作用)如下:
User::with('collections.game')->whereHas('collections.game', function ($query) {
return $query->where('status', '<>', 'denied');
})->get()
我的問題是所有游戲記錄都被回傳,包括那些denied狀態。我在四處閱讀,似乎上述內容應該有效,但事實并非如此。
我究竟做錯了什么?
uj5u.com熱心網友回復:
你不能這樣做whereHas('collections.game', ...)。您必須執行 a whereHasof a whereHas:
User::with('collections.game')
->whereHas('collections', function (Builder $query) {
return $query->whereHas('game', function (Builder $query) {
return $query->where('status', '<>', 'denied');
})
})
->get()
uj5u.com熱心網友回復:
我相信您將需要對with()子句進行過濾,因為whereHas()只會過濾用戶資料,但急切加載的關系不會自動包含該過濾器。
User::with(['collections.game' => function ($query) {
return $query->where('status', '<>', 'denied');
}])
->whereHas('collections.game', function ($query) {
return $query->where('status', '<>', 'denied');
})->get()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/416433.html
標籤:
