php - 如何将 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();
}
解决方案
这将满足您的需要。
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
推荐阅读
- javascript - 从“脚本”标签传递到 Django 中的单独 js 文件时,JS 代码不起作用
- amazon-web-services - 由于格式错误的 Json,策略角色无效?AWS
- python - 连接数据框中除 NaN 之外的所有列
- r - 在列表中的每个 xts 对象中的每个系列上复制 colMeans 函数
- angular - Formbuilder 嵌套验证
- javascript - Vue如何使用计算属性选择组件中的所有文本
- html - HTML 和 CSS 中的重叠表
- windows - 在 Windows 10 中伪造显示?
- ffmpeg - 为什么剪辑视频要花费这么多时间和cpu?
- javascript - React hook如何在父级重新渲染时避免执行子组件