MySQL 如何使用 Laravel 的流畅查询构建器选择计数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13223512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:22:19  来源:igfitidea点击:

How to select count with Laravel's fluent query builder?

mysqlactiverecordfluentlaraveleloquent

提问by Alex Naspo

Here is my query using fluent query builder.

这是我使用 fluent 查询构建器的查询。

    $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

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!

我将如何使用 Laravel 的流畅查询构建器进行这个选择?我知道我可以使用原始 sql 查询,但如果可能的话,我想避免这种情况。任何帮助将不胜感激,提前致谢!

回答by TLGreg

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:

您可以在 select() 中使用数组来定义更多列,并且可以在那里使用 DB::raw() 并将其别名为关注者。应该是这样的:

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

回答by Sinan Eldem

$count = DB::table('category_issue')->count();

will give you the number of items.

会给你物品的数量。

For more detailed information check Fluent Query Buildersection in beautiful Laravel Documentation.

有关更多详细信息,请查看精美的 Laravel 文档中的Fluent Query Builder部分。