简体   繁体   English

Laravel Query Builder从加入计算

[英]Laravel Query Builder count from join

So in my database I have table called website_tags , which contains id, title and so on, and also I have table called websites , with similar construction. 所以在我的数据库中,我有表名为website_tags ,其中包含id, title等,也有我表中调用websites ,类似的建筑。 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 . 还有一个名为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? 因此,我将在2个网站中使用“男人”标签,并在1中使用“女人”标签。 我应该如何构建查询? For now I have: 现在我有:

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中的行。

You have to define groupBy so 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM