如何将 mySQL 查询转换为 Laravel 5.4 查询生成器

How to convert mySQL Query to Laravel 5.4 Query Builder

请有人帮助我将此 SQL 查询转换为 Laravel 5.4 查询生成器语法。我已经搜索了解决方案并找到了一些但并不完全符合我的要求。

我有 3 个表:

供稿: - feed_id - user_id - feed_title

用户: - ID - 用户名

评论: - comment_id - feed_id - 文本 - user_id

在返回的视图中,我想查看供稿标题、用户的用户名以及每个供稿的所有评论数。就像您在 Facebook 上看到的那样:显示每个 post 显示的评论数量。拜托,我真的需要这样做:

这是我在 MySQL 数据库中尝试的 SQL 代码,它在那里可以正常工作,但是 returns 当我尝试在 Laravel 中实现相同的代码时出现错误

select *, count(comments.comment_id) as comment_count 
from `feeds` 
inner join `users` on 
`feeds`.`user_id` = `users`.`id` 
inner join `comments` on 
`feeds`.`feed_id` = `comments`.`comment_feed_id` 
group by `comments`.`comment_feed_id`

这应该可以做到,假设您的模型名称是 "Feed":

Feed::selectRaw('feeds.*, count(comments.comment_id) as comment_count')
->join('users', 'users.id', '=', 'feeds.user_id')
->join('comments', 'feeds.feed_id', '=', 'comments.comment_feed_id')
->groupBy('comments.comment_feed_id')->get();
DB::table('feeds')
    ->selectRaw('*, count(comments.comment_id) as comment_count')
    ->join('users', 'users.id', '=', 'feeds.user_id')
    ->join('comments', 'feeds.id', '=', 'comments.comment_feed_id')
    ->groupBy('comments.comment_feed_id')
    ->get();