【问题标题】:Laravel 8 - Limit joined tablesLaravel 8 - 限制连接表
【发布时间】:2022-01-18 22:50:30
【问题描述】:

所以我的数据结构如下:

User

  • id

Collection

  • user_id
  • game_id

Game

  • id
  • status

在我的模型中,我有这样的关系:

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 状态的记录。我在四处阅读,上面的方法似乎应该有效,但事实并非如此。

我做错了什么?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    你不能这样做whereHas('collections.game', ...)。你必须做一个whereHas 的一个whereHas

    User::with('collections.game')
        ->whereHas('collections', function (Builder $query) {
            return $query->whereHas('game', function (Builder $query) {
                return $query->where('status', '<>', 'denied');
            })
        })
        ->get()
    

    【讨论】:

    • 行得通。非常感谢您的回复。您能否将我指向更详细讨论此问题的文档部分,以便我更好地理解 为什么 它有效?我在文档中看到了对whereHas 的引用,但我对嵌套及其如何发挥作用更感兴趣。谢谢!
    【解决方案2】:

    我相信您需要在 with() 子句上使用过滤器,因为 whereHas() 将仅过滤用户数据,但急切加载的关系不会自动包含该过滤器。

    User::with(['collections.game' => function ($query) {
            return $query->where('status', '<>', 'denied');
        }])
        ->whereHas('collections.game', function ($query) {
            return $query->where('status', '<>', 'denied');
        })->get()
    

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多