猝不及防的犯了个基础问题
错误代码
// 统计的模型
$modelCount = AdminSms::Where('is_refuse',AdminSms::NO);
$count = [
'a' => $modelCount->where('msg','!=','')->count(),
'b' => $modelCount->where('msg_b','!=','')->count(),
'a_code' => $modelCount->where('getcodetime','!=',0)->count(),
'b_code' => $modelCount->where('getcodetime_b','!=',0)->count(),
];
4次sql执行
1. select * from admin_sms where is_refuse = 1 and msg != '';
2. select * from admin_sms where is_refuse = 1 and msg != '' & msg_b != '';
3. select * from admin_sms where is_refuse = 1 and msg != '' & msg_b != '' & getcodetime != 0;
4. select * from admin_sms where is_refuse = 1 and msg != '' & msg_b != '' & getcodetime != 0 & getcodetime != 0;
忘记 $modelCount
是一个存在的变量了,导致一直叠加 where
。
改正代码
// 统计的模型
$modelCount = AdminSms::Where('is_refuse',AdminSms::NO);
$count = [
'a' => (clone $modelCount)->where('msg','!=','')->count(),
'b' => (clone $modelCount)->where('msg_b','!=','')->count(),
'a_code' => (clone $modelCount)->where('getcodetime','!=',0)->count(),
'b_code' => (clone $modelCount)->where('getcodetime_b','!=',0)->count(),
];
我以前也犯过这种错 :joy:
直接一条语句查出来不是更好?
一样
应该一次查出来,然后用数组count
这样不也是4次查询吗
先查出来,然后用集合的where方法过滤,再count(),这样更好吧
给第一条sql加个get呗
第一条直接get 全部查出来,用集合的where 去查不是会更好点。。
同样踩过此坑
感谢楼主分享,之前一直找不到 clone 的使用场景 :joy:
我一般先查出来,再用collection的方法,也不用转数组,collection比数组还好用。
@Sher 这种方法只适合在数据量不大的情况下用
get出来然后用集合方法。建议多看看文档的集合方法,常用的都有,功能强大,代码写起来更简洁
sum if