Laravel Query Builder 从加入计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37673626/
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-09-14 13:56:42  来源:igfitidea点击:

Laravel Query Builder count from join

phpmysqllaravelquery-builder

提问by Coffee

So in my database I have table called website_tags, which contains id, titleand so on, and also I have table called websites, with similar construction. And also there is table called assigned_tags, which contains relation between tags and websites, so it contains relation id, tag_id and website_id.

所以在我的数据库中,我有一个名为 的表website_tags,其中包含id, title等等,还有一个名为 的表websites,具有类似的结构。还有一个叫做 的表assigned_tags,它包含标签和网站之间的关系,所以它包含关系id, tag_id and website_id

What I need is to join these tables with query, I need to get all the tags and count how many times these tags are used. So, for example website_tags contains following information:

我需要的是将这些表与查询连接起来,我需要获取所有标签并计算这些标签的使用次数。因此,例如 website_tags 包含以下信息:

1: men
2: women

And assigned tags contains like id: tag_id: website_id

并且分配的标签包含像 id: tag_id: website_id

1: 1: 1
2: 1: 2
3: 2: 2

So I will get that tag 'men' is used in 2 websites and tag 'women' is used in 1. How should I build the query?For now I have:

因此,我将在 2 个网站中使用标签“男性”,在 1 个网站中使用标签“女性”。我应该如何构建查询?现在我有:

DB::table('website_tags')
->join('assigned_tags', 'website_tags.id', '=', 'assigned_tags.tag_id')
->select('website_tags.id as id', 'website_tags.title as title', DB::raw("count(assigned_tags.tag_id) as count"))-
>get();

But this is wrong, this query just counts rows in assigned_tags.

但这是错误的,这个查询只计算assigned_tags 中的行数。

回答by KuKeC

You have to define groupByso query will know how to count it (just like in the regular SQL)

您必须定义,groupBy以便查询知道如何计算它(就像在常规 SQL 中一样)

Try something like this

尝试这样的事情

DB::table('website_tags')
->join('assigned_tags', 'website_tags.id', '=', 'assigned_tags.tag_id')
->select('website_tags.id as id', 'website_tags.title as title', DB::raw("count(assigned_tags.tag_id) as count"))
->groupBy('website_tags.id')
->get();