如何将mySQL查询转换为Laravel 5.4查询生成器 [英] How to convert mySQL Query to Laravel 5.4 Query Builder

查看:62
本文介绍了如何将mySQL查询转换为Laravel 5.4查询生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Please someone should help me convert this SQL Query to Laravel 5.4 Query Builder syntax. I have searched for solutions and found some but not exactly as I wanted.

我有3张桌子:

进料: -feed_id - 用户身份 -feed_title

Feeds: - feed_id - user_id - feed_title

用户: - ID -用户名

Users: - id - username

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

Commments: - comment_id - feed_id - text - user_id

在返回的视图上,我想查看提要标题,用户的用户名以及对每个提要的所有注释的计数.就像您在Facebook上看到的一样:在显示的每个帖子上显示评论数量.请我真的需要这样做:

On my view returned, I want to see the feed title, user's user name, and a count of all comments to each feed. Like what you see on facebook: displaying the amount of comments on each post displayed. Please I really need this to be done:

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

This is the SQL code I tried in MySQL Database, it kinda works there but returns an error when I try to implement the same in 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`

推荐答案

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();

这篇关于如何将mySQL查询转换为Laravel 5.4查询生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆