【问题标题】:Nested eager loading constraints嵌套急切加载约束
【发布时间】:2016-12-28 04:43:32
【问题描述】:

Post::with('cmets.owner')->get();

此查询将为我们提供所有帖子、其 cmets 和评论所有者。

但是我怎样才能得到所有的帖子,它的 最后 5 cmets 和每个 cmets 的作者。有人可以帮忙吗?

这是架构 帖子 - id - 内容 评论 - id - commented_id (user_id) - user_id 用户 - id - full_name 谢谢

【问题讨论】:

  • 请发布您的数据库架构
  • 帖子 - id - 内容评论 - id - commented_id (user_id) - user_id 用户 - id - 全名

标签: laravel-5 eloquent


【解决方案1】:

试试这个:

$posts = Post::with(['comments'=>function($query){
                $query->orderBy('created_at','desc')->limit(5);
            }])
            ->with('comments.author')
            ->get();

【讨论】:

  • 对不起,这没有按预期工作。它返回所有的cmets。我只需要最后 5 个请查看下面运行的查询 select * from posts select * from comments where comments .post_id in ('6', '7', '8', '9', ' 10'、'11'、'12'、'13'、'14'、'15'、'16'、'17'、'18'、'19'、'20'、'21'、'22' , '23', '24', '25', '26')
  • 两个选择语句?
  • 是的,急切加载不会使用连接。它生成多个查询
  • take(5) 怎么样?
  • @jaysingkar 在 Laravel 中,您可以像 Model::orderBy('created_at, 'desc')->take(5) 一样检索 5 个最新项目。但当我打字时,我意识到这可能与limit(5) 的方法相同。当我写上一条评论时,我还在醒来。
猜你喜欢
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
相关资源
最近更新 更多