猝不及防的犯了个基础问题

错误代码

// 统计的模型        
$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(),
];
专心学习不瞎搞
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 14

我以前也犯过这种错 :joy:

3年前 评论

直接一条语句查出来不是更好?

3年前 评论
Epona

应该一次查出来,然后用数组count

3年前 评论
xiaohuasheng 2年前
Epona (作者) 2年前

这样不也是4次查询吗

3年前 评论

先查出来,然后用集合的where方法过滤,再count(),这样更好吧

3年前 评论

给第一条sql加个get呗

3年前 评论

第一条直接get 全部查出来,用集合的where 去查不是会更好点。。

3年前 评论

感谢楼主分享,之前一直找不到 clone 的使用场景 :joy:

3年前 评论

我一般先查出来,再用collection的方法,也不用转数组,collection比数组还好用。

3年前 评论

@Sher 这种方法只适合在数据量不大的情况下用

3年前 评论

get出来然后用集合方法。建议多看看文档的集合方法,常用的都有,功能强大,代码写起来更简洁

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!