首页 > 解决方案 > 如何将 SQL“IN”循环查询从 1 简化为同一查询中的多个 IN 检查?

问题描述

我正在尝试简化这部分代码,其中我将循环数据库查询调用为单个数据库查询,然后我对结果运行循环。

我现在的问题是,我如何不仅可以获得 app_categories 表中存在行的一个类别的应用程序数量,而且每个类别的结果同时计算?

当前代码:

    foreach(DB::Table('categories')->get() as $category)
    {
        $appcount[$category->name] = DB::Table('apps')->where('active', 1)
            ->whereRaw('apps.id in (select app_id from app_categories where category_id = ?)', [$category->id])
            ->count();
    }

标签: phpmysqlsqllaravellaravel-5

解决方案


这将满足您的需要。

DB::table('categories')
    ->select('categories.id as category_id','categories.name as name',DB::raw('count(*) as apps_count'))
    ->leftJoin('app_categories','categories.id','=','apps_categories.category_id')
    ->leftJoin('apps','apps.id','=','apps_categories.app_id')
    ->where('apps.active',1)
    ->groupBy('categories.id')

另一种解决方案是使用雄辩的关系

https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models


推荐阅读