有些时候,并不需要获取关联数据,而只是希望获取关联数据的统计。
例如用户模型与用户充值订单模型,
想知道用户充值了多少次,则用withCount,
想知道用户充值了多少钱,则用withSum,
想知道充值的最大一笔的金额用withMax,
想知道充值的最小一笔的金额用withMin,
想知道充值的平均的金额withAvg
User模型用增加一对多模型关联
public function recharge(){
return $this->hasMany("recharge",'user_id','id');
}
控制器中调用,关联统计功能会在模型的对象属性中自动添加一个以“关联方法名+_方法”(支持自定义)为名称的动态属性来保存相关的关联统计数据。
$list = User::withCount('recharge')
->withSum("recharge",'cost')
->withMax("recharge",'cost')
->withMin("recharge",'cost')
->withAvg("recharge",'cost'))
->select([1,2,3]);
foreach($list as $user){
echo $user->recharge_count;//充值的数量
echo $user->recharge_sum//充值的总金额
echo $user->recharge_max//充值的最大金额
echo $user->recharge_min//充值的最小金额
echo $user->recharge_avg//充值的平均金额
}
#如果要自定义字段名,则用数组的形式
$list = User::withCount(['recharge'=>'aa'])
->withSum(["recharge"=>'bb'],'cost')
->withMax(["recharge"=>'cc'],'cost')
->withMin(["recharge"=>'dd'],'cost')
->withAvg(["recharge"=>'ee'],'cost')
->select([1,2,3]);
foreach($list as $user){
echo $user->aa;//aa充值的数量
echo $user->bb;//aa充值的总金额
echo $user->cc;//cc充值的最大的一笔的金额
echo $user->dd;//dd充值的最小的一笔充值金额
echo $user->ee;//ee充值的平均金额
}
关联统计仅针对一对多或者多对多的关联关系,并且暂不支持远程一对多
以上方法都是默认用了子查询,如果想
withCount()
生成的sql语句是
SELECT *,(SELECT COUNT(*) AS tp_count FROM `recharge` `count_table` WHERE ( `count_table`.`user_id` =user.id )) AS `as`,(SELECT SUM(`cost`) AS tp_sum FROM `recharge` `sum_table` WHERE ( `sum_table`.`user_id` =user.id )) AS `aa`,(SELECT MAX(`cost`) AS tp_max FROM `recharge` `max_table` WHERE ( `max_table`.`user_id` =user.id )) AS `cc`,(SELECT MIN(`cost`) AS tp_min FROM `recharge` `min_table` WHERE ( `min_table`.`user_id` =user.id )) AS `recharge_min`,(SELECT AVG(`cost`) AS tp_avg FROM `recharge` `avg_table` WHERE ( `avg_table`.`user_id` =user.id )) AS `recharge_avg` FROM `user` LIMIT 1
如果不用子查询,withCount()第二个参数填false,withSum,withMax,withMin,withAvg第三个参数填false,
生成的sql语句是
SELECT * FROM `user` LIMIT 1 [ RunTime:0.001382s ]
SHOW COLUMNS FROM `recharge` [ RunTime:0.002308s ]
SELECT COUNT(*) AS tp_count FROM `recharge` WHERE `user_id` = 100001
SELECT SUM(`cost`) AS tp_sum FROM `recharge` WHERE `user_id` = 100001
SELECT MAX(`cost`) AS tp_max FROM `recharge` WHERE `user_id` = 100001
SELECT MIN(`cost`) AS tp_min FROM `recharge` WHERE `user_id` = 100001
SELECT AVG(`cost`) AS tp_avg FROM `recharge` WHERE `user_id` = 100001
``
网友评论