【问题标题】:Laravel Eloquent - Define relationship to one of three possible tables based on value of column in parent tableLaravel Eloquent - 根据父表中列的值定义与三个可能表之一的关系
【发布时间】:2016-11-10 08:16:15
【问题描述】:

假设我有一篇带有评论部分的博文。使用 Laravel Eloquent 我从“cmets”表和关系“用户”表中获取数据。像这样的:

Comment::where('post_id', $post_id)
       ->with('user')
       ->get();

“users”表有一个名为“user_type”的列,其值为“user”或“admin”。

如果users 表中的user_typeuser,我想从regular_users 表中获取关系数据,如下所示:->with(user.regular_user)

如果users 表中的user_typeadmin 我想从admins 表中获取关系数据,如下所示:->with('user.admin')

(所有关系都在模型中正确定义。)

我该怎么做?

【问题讨论】:

  • 可以在mysql中创建视图
  • 为什么不直接加载两者,不管类型如何? with('user', 'user.regular_user', 'user.admin')

标签: php mysql laravel eloquent relationship


【解决方案1】:

使用 whereHas 代替 with,尝试以下操作:

即:

$regular_users = Comment::where('post_id', $post_id)
   ->whereHas('user',function ($user) {
       $user->where('user_type', 'user')->with('regular_user');
   })       
->get();

【讨论】:

  • N+1 问题!这是一个性能杀手问题;)我强烈建议删除答案!
  • 是的,你说得对。像这样进行查询调用不是最好的。雄辩的whereHad 函数在这里可能更有意义。
猜你喜欢
  • 1970-01-01
  • 2020-05-06
  • 2021-01-14
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 2022-01-19
  • 2020-10-25
  • 1970-01-01
相关资源
最近更新 更多