Laravel雄辩的多个AND / OR语句

时间:2019-01-15 14:33:24

标签: mysql laravel eloquent

我正在尝试从该数据库检索属于特定日期范围或为NULL的产品。另外,必须以前购买过这些产品。

我的查询:

$offerings = Offering::with(['items' => function($query) use ($purchased, $dt) {
            $query->whereNotIn('offering_items.id', $purchased)
                  ->whereDate('offering_items.start_date', '<=', $dt->toDateString())
                  ->whereDate('offering_items.end_date', '>=', $dt->toDateString())
                  ->orWhereNull('offering_items.start_date')
                  ->orWhereNull('offering_items.end_date');
        }])->get();

表结构: enter image description here

表: enter image description here

此查询的结果输出数据库中的所有记录。

我看不到我在做什么错。

2 个答案:

答案 0 :(得分:0)

尝试将wheres分组,如下所示:

Offering::with(['items' => function($query) use ($purchased, $dt) {
    $query->where(function($query){
    $query->whereNull('start')->orWhereNull('end');
})->orWhere(function($query){
    $query->whereDate('offering_items.start_date', '<=', $dt->toDateString())->whereDate('offering_items.end_date', '>=', $dt->toDateString())
})->whereNotIn('offering_items.id', $purchased)
}])->get();

答案 1 :(得分:0)

此代码最终获得了预期的结果:

$offerings = Offering::with(['items' => function($query) use ($purchased, $dt) {
            $query->where(function($query) use ($purchased) {
                $query->whereNotIn('offering_items.id', $purchased);
            })->where(function($query) use ($dt) {
                $query->whereDate('offering_items.start_date', '<=', $dt->toDateString())
                      ->orWhereNull('offering_items.start_date');   
            })->where(function($query) use ($dt) {
                $query->whereDate('offering_items.end_date', '>=', $dt->toDateString())
                ->orWhereNull('offering_items.end_date');
            });
            }])->get();