【发布时间】:2022-01-03 12:20:54
【问题描述】:
我有两个名为 Posts 和 Comments 的表。
帖子表的样子。
|id|user_id|content|created_at|updated_at|
|1 | 24 |demotxt|demo_date |demo_date |
|2 | 21 |domotxt|demo_date2|demo_date2|
|3 | 24 |domotxt|demo_date2|demo_date3|
|4 | 28 |dimotxt|demo_date3|demo_date5|
评论表看起来像
|id|user_id|post_id|comment |created_at|updated_at|
|1 | 24 | 3 |comment1|demo_date |demo_date |
|2 | 21 | 3 |xyadbsss|demo_date2|demo_date2|
|3 | 24 | 1 |okayokay|demo_date2|demo_date3|
|4 | 28 | 4 |somehtin|demo_date3|demo_date5|
我想要实现的是获得第一个最新评论和每个帖子的 cmets 总数。 即
|post_id|latest_comment |total_comments |
| 3 |xyadbsss |2 |
| 1 |okayokay |1 |
| 4 |somehtin |1 |
这是我试过的sql查询
SELECT post_id, count(post_id) total_comments, comment latest_comment
FROM `comments`
LEFT JOIN posts on comments.post_id = posts.id
GROUP BY post_id;
这是给我的
|post_id|latest_comment |total_comments |
| 3 |comment1[not latest]|2 |
| 1 |okayokay |1 |
| 4 |somehtin |1 |
【问题讨论】:
-
使用 eloquent 关系 +
withCount获取 cmets 的计数。使用另一个with('latestComment')并在后模型上定义这两个关系。 -
@BhaumikPandhi 没有其他办法。我的意思是我已经使用了 withCount 但无论如何我都不能使用 count 来操纵查询以获取最新评论。
-
你使用的是什么版本的 Laravel?另外,您是否为
posts和comments设置了模型/关系? -
@Rwd 我正在使用 Laravel 8 。是的,所有关系都是针对 Post 和 Comment 模型
-
要获得将多行合并为一行的结果所需的计数。一旦发生这种情况,您将丢失有关单个行的所有信息,因此唯一的方法是通过子查询或使用"windowing",它的作用类似于分组但不会将组折叠到单行。我一直觉得“GROUP BY”是一个非常令人困惑的名字,我认为称它为“AGGREGATE ON”会消除很多困惑