You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中含SELECT与COUNT的SQL查询转Eloquent实现求助

没问题,我来帮你把这条SQL转换成Laravel Eloquent的实现,两种方式都给你列出来,你可以根据自己的情况选:

方式一:使用Eloquent模型(推荐,更符合Laravel的ORM风格)

首先假设你已经创建了对应的数据表模型:Tag对应tags表,PlanificacionInfo对应planificacion_info表。先在Tag模型里定义关联关系:

// app/Models/Tag.php
public function planificacionInfos()
{
    // 关联关系:一个Tag对应多个PlanificacionInfo,外键是planificacion_info.id_area,关联Tag的id_tag
    return $this->hasMany(PlanificacionInfo::class, 'id_area', 'id_tag');
}

然后就可以用withCount来实现统计查询,还能自定义统计字段的别名:

$intervencionesPorArea = Tag::where('grupo', 'area')
    ->where('estado', true)
    ->withCount([
        'planificacionInfos as cantidad_intervenciones' => function ($query) {
            $query->select(DB::raw('count(id_area)'));
        }
    ])
    ->groupBy('desc')
    ->select('desc') // 只选中需要的字段,提升性能
    ->get();

方式二:直接使用查询构造器(和原始SQL结构最接近)

如果不想定义模型关联,直接用DB门面的查询构造器也能快速实现,和你的原始SQL几乎一一对应:

use Illuminate\Support\Facades\DB;

$intervencionesPorArea = DB::table('tags')
    ->join('planificacion_info', 'planificacion_info.id_area', '=', 'tags.id_tag')
    ->where('tags.grupo', 'area')
    ->where('tags.estado', true)
    ->select(
        'tags.desc',
        DB::raw('COUNT(planificacion_info.id_area) as cantidad_intervenciones')
    )
    ->groupBy('tags.desc')
    ->get();

小提醒:如果你的Laravel开启了数据库严格模式(默认是开启的),有些数据库(比如MySQL)可能会要求groupBy包含所有非聚合字段,不过这里我们只选中了tags.desc,所以不会有问题。如果后续扩展字段出现报错,可以在config/database.php里把mysql配置下的strict设为false,或者把所有选中的字段都加入groupBy。

内容的提问来源于stack exchange,提问作者Matías Ramírez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:03:25