【问题标题】:Laravel Query Builder count from join加入的 Laravel 查询生成器计数
【发布时间】:2016-10-07 00:25:00
【问题描述】:

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

所以我会得到标签 'men' 在 2 个网站中使用,标签 'women' 在 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();

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

【问题讨论】:

    标签: php mysql laravel query-builder


    【解决方案1】:

    您必须定义 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();
    

    【讨论】:

      猜你喜欢
      • 2013-08-07
      • 2016-03-09
      • 2014-04-10
      • 2017-06-24
      • 2021-07-04
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多