Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用whereYear Laravel查询生成器在值为空时切换到其他字段_Php_Laravel_Builder - Fatal编程技术网

Php 使用whereYear Laravel查询生成器在值为空时切换到其他字段

Php 使用whereYear Laravel查询生成器在值为空时切换到其他字段,php,laravel,builder,Php,Laravel,Builder,我对使用whereYear在第二个字段为空时打开其他字段有疑问 比如说,我们有这个数据库表 +------------+------------+ | field_one | field_two | +------------+------------+ | 2020 | NULL | +------------+------------+ 当field\u two的值为空时,我想切换到field\u one。使用或where不起作用,因为如果条件不匹配或为fals

我对使用
whereYear
在第二个字段为空时打开其他字段有疑问

比如说,我们有这个数据库表

+------------+------------+
| field_one  | field_two  |
+------------+------------+
| 2020       | NULL       |
+------------+------------+
field\u two
的值为空时,我想切换到
field\u one
。使用
或where
不起作用,因为如果条件不匹配或为false,则
或where
会切换到字段1。我不确定
在哪里是解决这个问题的方法

$year = Carbon::now()->year;
$table = DB::table('my_table')
            ->where(function($table) use ($year) {
                $table->whereYear('year', '=', $year)
                      ->orWhereYear('year', '=', $year);
            })->count();

提前谢谢你

您可以使用原始查询结合
IFNULL()
-
whereYear()
基本上将MySQL函数
YEAR()
应用于日期时间,我们可以手动将其与
IFNULL()
组合,如果第一列为
NULL
,则选择第二列

$year=Carbon::now()->year;
$table=DB::table('my_table'))
->whereRaw(“年(如果为空(字段1,字段2))=?,[$YEAR])
->计数();

即使不指定表名,它也可以工作。谢谢你,奇雷尔!