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

标签 laravel where-clause

尝试在 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();

仅当这些字段不为 NULL 时,我才想在publish_to 和publish_from 上应用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 语句对于条件 where 不太好......所以你真正想要的是 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(),如果您要求的话,这会更好一点我。

关于Laravel:如何仅在字段值不为 NULL 时应用 where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32312459/

相关文章:

c++ - xtensor xt::where与索引相关的功能出现问题

mysql - SQL选择符合条件的数据,先显示,然后对剩余数据进行排序

php - 使用 Relation Laravel 5.1 创建记录

laravel - 如何通过redirect()传递数据

php - SQLSTATE[HY000] : General error: 1005 Can't create table - Laravel 4

MySQL 多选不明确结果

mysql - 有人可以推荐一个关于 MySQL 索引的好教程,特别是在连接期间在 order by 子句中使用时吗?

php - WHERE 条件下的变量

php - 使用两列自动递增(laravel 4.1)

php - 需要关系数的意见