Laravel 初始化查询的多种用途
我的模型中有这个查询初始化:
$query = Mymodel::where('is_active', 1);
我用它来获得不同的结果:
$result1 = $query->where('stat', null)->count();
$result2 = $query->where('stat', '!=', null)->count();
我的数据库中有 4 行,其中 2 行统计为 null,2 行不为 null;所以我期望 $result1 和 $result2 值为 2;但我得到 $result1 是 2,$result2 是 0;
就好像 $result2 查询有 2 个条件 null 和 not null;
I have this init of query in my model:
$query = Mymodel::where('is_active', 1);
i use it to get different result:
$result1 = $query->where('stat', null)->count();
$result2 = $query->where('stat', '!=', null)->count();
i have 4 rows in my database, 2 of them have stat null and 2 is not null; so i expect that $result1 and $result2 value are 2; but i got that $result1 is 2 and $result2 is 0;
as if the $result2 query has the 2 conditions null and not null;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上不能像那样使用相同的查询。
where
子句将修改原始的$query
对象,因此您的计数会略有偏差。您应该克隆原始文件,或者将其定义为范围:
clone
方法:scope
方法:Mymodel.php
:然后在您的代码中:
You can't really use the same query like that. The
where
clauses will modify the original$query
object, so your counts will be a little off.You should either clone the original, or define it as a Scope:
clone
Approach:scope
Approach:Mymodel.php
:Then in your code: