我有一个
customers
表和 Customer
作为模型。我正在尝试获取除 id 1 的客户类别之外的所有客户。 customer_category_id
可以为空。
我有以下疑问。
Customer::where('customer_category_id', '!=', 1)->with('customerMeta')->get();
以上查询没有为客户提供空客户类别 ID。会是什么原因呢?
我需要所有类别为 null 或类别不等于 1 的客户
任何建议都值得赞赏。
这应该有效:
Customer::where(function ($query) {
$query->where('customer_category_id', '!=', 1)
->orWhereNull('customer_category_id')
})
->with('customerMeta')
->get();
祝你好运!
因为
null
也不等于1
。您可能应该将 ->whereNotNull('customer_category_id')
添加到您的查询中:
Customer::where('customer_category_id', '!=', 1)
->whereNotNull('customer_category_id')
->with('customerMeta')
->get();
该查询应该有效。
您可以尝试在
artisan tinker
中运行它。在运行查询之前激活查询日志记录:
DB::connection()->enableQueryLog();
然后运行查询。
然后运行:
DB::getQueryLog();
您现在将看到创建的查询。将此查询复制到 SQL 客户端并对其进行调整。
希望这有帮助。
像这样更改您的查询:
Customer::where('customer_category_id', '!=', '1')->with('customerMeta')->get();
因为 1 也意味着
true
,所以你必须使用字符串。
如果您还想返回
null
类别,您可以使用 whereNull
Customer::where('customer_category_id', '!=', 1)
->whereNull('customer_category_id')
->with('customerMeta')
->get();
或者您可以使用多个
where
子句,如下所示:
$query->where([
['customer_category_id', '!=', '1'],
['customer_category_id', '=', null],
...
])
这不是 Laravel 的问题,而是 MySQL 的问题 处理空值时,最好使用 NULL 安全等于运算符 <=> ( https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_equal-to )
Customer::whereNot('customer_category_id', '<=>', 1)->with('customerMeta')->get();