[英]How to get a specific column from the joined table in HasMany relationship in Laravel Eloquent
[英]How to do a JOIN on table in a HasMany relationship, if only the latest row on the joined table is searched or?
我有一个帖子和帖子评论 model。 如图所示,他们处于 HasMany 关系中。 ER图
我需要返回所有帖子,并且每个帖子的最新评论,分页。
问题是我还需要对“post_comments”表进行搜索。 诸如“获取特定用户的所有帖子,......”之类的东西。 所以我决定使用JOIN。
我的问题是,使用 JOIN 时,我不会在每个帖子中只收到一个条目,而是会收到与相关表中的评论一样多的帖子条目。
我试图按“post_id”对结果进行分组,但一些批评者说这不好。 什么是“正确的方法”?
由于您使用的是 laravel 而不是纯 PHP ,因此正确的方法是为此使用 eloquent ,所以一般的想法是这样
$posts = Post::whereHas('comments')->with('comments')->paginate(10);
然后当你在你的刀片或 vue 中 foreach 这些帖子时,你只需要这样做
foreach($posts as $post) {
$post->comments()->latest()->first(); // this the latest comment
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.