如何让所有评论过和没有评论过的用户

时间:2021-04-26 04:47:38

标签: php sql database laravel

我正在尝试生成一个评论者列表,而不是像这样的每个帖子:

<头>
id post_id user_id 文字 created_at
1 1 1 测试 时间戳
2 1 2 测试 时间戳
3 1 3 - -
4 1 4 - -
5 1 5 - -
6 1 6 - -
7 2 1 - -
8 2 2 - -
9 2 3 - -
10 2 4 - -
11 2 5 测试 时间戳
12 2 6 - -

这是我的表格:

帖子表:

<头>
id 标题 created_at
1 发布 1 时间戳
2 帖子 2 时间戳

评论表:

<头>
id post_id user_id 文字 created_at
1 1 1 测试 时间戳
2 1 2 测试 时间戳
3 2 5 测试 时间戳

用户表:

<头>
id 姓名 created_at
1 阿尔法 时间戳
2 加油 时间戳
3 查理 时间戳
4 增量 时间戳
5 回声 时间戳
6 狐步 时间戳

这可能吗?我已经尝试过下面的这段代码,但是当我用 post_id 过滤它时,它只显示评论过的用户。

QueryBuilder::for(Comments::class)
->rightJoin(
  'users',
  'comments.user_id',
  'users.id',
)
->select(
  'comments.id',
  'users.id',
  'comments.post_id',
  'comments.text',
  'comments.updated_at'
)
->allowedFilters([
  'post_id',
])

2 个答案:

答案 0 :(得分:0)

使用 MySQL,您可以通过尝试以下代码来实现:

SELECT case when comments.id is null then '-' else comments.id end,
       case when posts.id is null then '-' else posts.id end,
       case when users.id is null then '-' else users.id end,
       case when comments.text is null then '-' else comments.text end,
       case when comments.created_at is null then '-' else comments.created_at end
       FROM posts
LEFT JOIN comments ON comments.post_id=posts.id
LEFT JOIN users ON users.id=comments.user_id

答案 1 :(得分:0)

使用 cross join 生成行,然后使用 left join 引入现有数据:

select p.id as post_id, u.id as user_id, c.text, c.created_at
from posts p cross join
     users u left join
     comments c
     on c.post_id = p.id and c.user_id = u.id
order by p.post_id, u.user_id;

这不会枚举行。如果需要,可以将 row_number() 用于第一列:

select row_number() over (order by p.id, u.id) as id,
       p.id as post_id, u.id as user_id, c.text, c.created_at
from posts p cross join
     users u left join
     comments c
     on c.post_id = p.id and c.user_id = u.id
order by p.post_id, u.user_id;
相关问题