ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
LaravelORM 写法: ~~~ Orm::withCount['relation'])->get(); ~~~ 解析成SQL : ~~~ select `a`.*, (select count(*) from `relation` where `a`.`id` = `relation`.`aid`) as `relation_count` from `a`; ~~~ 当需要统计关联的 某个字段 sum 时,可以这样写: ~~~ Orm::withCount(['relation as relation_sum' =>function($query){ $query->select(DB::raw("sum(amount) as relationsum"); }]) ~~~ 解析成SQL: ~~~ select `a`.*, (select sum(amount) from `relation` where `a`.`id` = `relation`.`aid`) as `relation_sum_count` from `a` ; ~~~ 其他的avg , max , min也可以通过withCount实现