Laravel:如何只在字段值不为NULL时才应用where条件

Laravel: How to apply where condition only when the field value is not NULL

正在尝试在 laravel 中编写查询:

 return DB::table('course_modules')->select('module_id', 'publish_from', 'publish_to')
                    ->where('course_id', $course_id)
                    ->where('is_deleted', '0')
                 ->orwhere('publish_from', '>=', date('Y-m-d H:i:s'))
                    ->orwhere('publish_to', '<=', date('Y-m-d H:i:s'))
                    ->orwhere(function($query) {
                                $query->where('publish_from', '>=', date('Y-m-d H:i:s'))
                                ->where('publish_to', '<=', date('Y-m-d H:i:s'));
                            })
                    ->where('hide_module', 1)
                    ->get();

我想仅在 publish_to 和 publish_from 字段不为 NULL 时应用 where 子句。

我想这样做:

 if(publish_from!=NULL){   ->orwhere('publish_from', '>=', date('Y-m-d H:i:s'))}   

同样的方式:

 if(publish_to!=NULL){   ->orwhere('publish_to', '>=', date('Y-m-d H:i:s'))}

没有得到确切的方法。帮助...

你必须重新考虑一下你的逻辑,因为 SQL 语句对于条件 wheres 不是很好......所以你真正想要的是 publish_frompublish_to要么 NULL 要么在某个范围内。

这应该可以做到:

return DB::table('course_modules')->select('module_id', 'publish_from', 'publish_to')
    ->where('course_id', $course_id)
    ->where('is_deleted', '0')
    ->where('hide_module', 1)
    ->where(function($q){
        $q->where(function($q){
            $q->whereNull('publish_from')
              ->whereNull('publish_to');
        })->orWhere(function($q){
            $q->where('publish_from', '>=', date('Y-m-d H:i:s'))
              ->where('publish_to', '<=', date('Y-m-d H:i:s'));
        });
    })
    ->get();

请注意,这里不一定需要两层嵌套闭包,但这样更易于阅读并避免错误。

另外,你可以把date('Y-m-d H:i:s')换成Carbon::now(),如果你问我这样更好一点。