因此,在我的数据库中,我有一个名为的表website_tags
,其中包含id, title
等,并且我也有一个名为的表websites
,其结构类似。还有一个叫的表assigned_tags
,它包含标签和网站之间的关系,因此它包含Relation id, tag_id and website_id
。
我需要的是将这些表与查询联接,我需要获取所有标签并计算使用这些标签的次数。因此,例如website_tags包含以下信息:
1: men
2: women
分配的标签包含以下ID:tag_id:website_id
1: 1: 1
2: 1: 2
3: 2: 2
因此,我将在2个网站中使用标签“ men”,在1个网站中使用标签“ women”。我应如何构建查询?现在,我有:
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();
但这是错误的,此查询仅对Assigned_tags中的行进行计数。
您必须定义,groupBy
以便查询将知道如何对其进行计数(就像在常规SQL中一样)
尝试这样的事情
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句