Laravel Eloquent,其中field为X或null [英] Laravel Eloquent where field is X or null
问题描述
我有一个这样的表:
table
- field1: tinyint
- field2: varchar (nullable)
- datefield: timestamp (nullable)
现在,我想获取field1为1,field2为null且datefield小于X或null的所有条目.我已经尝试过这样的事情:
Now I want to get all entries where field1 is 1, field2 is null and where datefield is smaller than X or null. I already tried something like this:
$query = Model::where('field1', 1)
->whereNull('field2')
->where('datefield', '<', $date)
->orWhereNull('datefield');
但是那是行不通的.我总是得到datefield为null的每个条目.其他字段是什么都没关系.我还尝试将其拆分为2个查询:首先获取datefield小于X或null的每一行,然后(基于它)获取field1为1且field2为null的每个字段.
but thats not working. I always get every entry where datefield is null. It doesn't matter what the other fields are. I also tried to split it in 2 queries: First get every row where datefield is smaller than X or null and then (based on it) get every field where field1 is 1 and field2 is null.
结果是相同的. 知道怎么做吗?
The result was the same. Any idea how to do this?
推荐答案
听起来您需要利用鉴于field1
和field2
中的搜索是恒定的,我们将保持不变,但我们将对datefield
中的搜索进行一些调整.
Given that search in field1
and field2
is constant we will leave them as is, but we are going to adjust your search in datefield
a little.
尝试一下:
$query = Model::where('field1', 1)
->whereNull('field2')
->where(function ($query) {
$query->where('datefield', '<', $date)
->orWhereNull('datefield');
}
);
如果您需要调试查询并查看其为何无法运行,则可以帮助查看其实际执行的SQL.您可以将->toSql()
链接到雄辩的查询的末尾以生成SQL.
If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql()
to the end of your eloquent query to generate the SQL.
这篇关于Laravel Eloquent,其中field为X或null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!