Laravel 初始化查询的多种用途

发布于 2025-01-13 23:33:22 字数 403 浏览 2 评论 0原文

我的模型中有这个查询初始化:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离旧人 2025-01-20 23:33:22

您实际上不能像那样使用相同的查询。 where 子句将修改原始的 $query 对象,因此您的计数会略有偏差。

您应该克隆原始文件,或者将其定义为范围:

clone 方法:

$baseQuery = Mymodel::where('is_active', 1);

$result1 = (clone $baseQuery)->whereNull('stat')->count();
$result2 = (clone $baseQuery)->whereNotNull('stat')->count();

scope 方法:

Mymodel.php

public function scopeActive($query) {
  return $query->where('is_active', 1);
}

然后在您的代码中:

$result1 = Mymodel::active()->whereNull('stat')->count();
$result2 = Mymodel::active()->whereNotNull('stat')->count();

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:

$baseQuery = Mymodel::where('is_active', 1);

$result1 = (clone $baseQuery)->whereNull('stat')->count();
$result2 = (clone $baseQuery)->whereNotNull('stat')->count();

scope Approach:

Mymodel.php:

public function scopeActive($query) {
  return $query->where('is_active', 1);
}

Then in your code:

$result1 = Mymodel::active()->whereNull('stat')->count();
$result2 = Mymodel::active()->whereNotNull('stat')->count();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文