使用 whereYear Laravel Query Builder 在值为 null 时切换到其他字段

Switching to other field when the value is null using whereYear Laravel Query Builder

我对使用 whereYear.

在第二个字段为空时打开其他字段有疑问

例如我们有这个数据库table

+------------+------------+
| field_one  | field_two  |
+------------+------------+
| 2020       | NULL       |
+------------+------------+

我想在 field_two 的值为 null 时切换到 field_one。使用 orWhere 不起作用,因为如果条件不匹配或为假,orWhere 会切换到字段一。我不太确定 orWhere 是否是解决此问题的方法。

$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("YEAR(IFNULL(field_one, field_two)) = ?", [$year])
            ->count();