🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
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实现