如何选择与Laravel的流畅查询生成器计数? [英] How to select count with Laravel's fluent query builder?
问题描述
下面是使用流利的查询生成器我的查询。
Here is my query using fluent query builder.
$query = DB::table('category_issue')
->select('issues.*')
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by(DB::raw('COUNT(issue_subscriptions.issue_id)'), 'desc')
->get();
正如你所看到的,我是从连接表的计数订购。这是工作的罚款。不过,我想用我的选择,返回此计数。
As you can see, I am ordering by a count from the joined table. This is working fine. However, I want this count returned with my selections.
下面是我的原续集查询工作正常。
Here is the my raw sequel query that works fine.
Select issues.*, COUNT(issue_subscriptions.issue_id) AS followers
FROM category_issue JOIN Issues ON category_issue.issue_id = issues.id
LEFT JOIN issue_subscriptions ON issues.id = issue_subscriptions.issue_id
WHERE category_issue.category_id = 1
GROUP BY issues.id
ORDER BY followers DESC
我怎么会去这个选择使用Laravel的流畅查询生成器?我知道我可以使用原始的SQL查询,但我想避免,如果可能的。任何帮助将是AP preciated,在此先感谢!
How would I go about this select using Laravel's fluent query builder? I am aware I can use a raw sql query but I would like to avoid that if possible. Any help would be appreciated, thanks in advance!
推荐答案
您可以使用一个数组中的选择()来定义多个列,您可以使用DB ::原始()有与它混叠追随者。应该是这样的:
You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:
$query = DB::table('category_issue')
->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by('followers', 'desc')
->get();
这篇关于如何选择与Laravel的流畅查询生成器计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!