Laravel 8.x - 如何将 updateOrCreate 与 where 子句一起使用?

Laravel 8.x - How to use updateOrCreate with a where clause?

我正在尝试使用 Laravel updateOrCreate 根据 ID 是否存在更新本月和上个月的记录。

\App\Models\Result::updateOrCreate(
        [
            'id' => $request->get('id'),
            // where created_at is within the last 2 months
            'created_at' => [
                '>',
                \Carbon\Carbon::now()->startOfMonth()->subMonthsNoOverflow()
            ],
        ],
        [
            'discipline_one' => $request->get('d-one'),
            'discipline_two' => $request->get('d-two'),
            'discipline_three' => $request->get('d-three'),
            'discipline_four' => $request->get('d-four'),
            'discipline_five' => $request->get('d-five'),
            'discipline_six' => $request->get('d-six'),
        ]
    );

如果 ID 存在,并且结果是当月或上个月,则创建新记录而不是更新。

Expected input: 1 (which exists from last month)
Expected output: Record is updated

Expected input: 2 (which doesn't exist or is not within 2 months)
Expected output: New record is created

更新:

使用建议的答案,

'id' => $request->get('id'),
'created_at' => \App\Models\Result::whereBetween('created_at', [
    \Carbon\Carbon::now()->startOfMonth()->subMonthsNoOverflow(),
    \Carbon\Carbon::now()->endOfMonth(),
]),

我收到错误:

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string

给你:

您只需显式在方法的第一个参数中定义运算符

方法的第一个参数中数组的每个元素都应该是一个包含三个参数的数组。
列、运算符、值

$startDate = \Carbon\Carbon::now()->startOfMonth()->subMonths(2);
$endDate = \Carbon\Carbon::now()->endOfMonth();

$resultRow = \App\Models\Result::query()
        ->where('id', $request->id)
        ->whereBetween('created_at', [$startDate, $endDate])
        ->first();

\App\Models\Result::updateOrCreate(
    [
        [
            'id', '=', $request->get('id'),
        ],
        [
            'created_at', '>=', $startDate,
        ],
        [
            'created_at', '<=', $endDate,
        ],
    ],

    array_merge(
        [
            'discipline_one' => $request->get('d-one'),
            'discipline_two' => $request->get('d-two'),
            'discipline_three' => $request->get('d-three'),
            'discipline_four' => $request->get('d-four'),
            'discipline_five' => $request->get('d-five'),
            'discipline_six' => $request->get('d-six'),
        ],

        $resultRow ? [] : [
            'id' => $request->get('id'),
            'created_at' => \Carbon\Carbon::now()
        ]
    )

);

请注意,我在方法的第二个参数中重复了 id & created_at 列设置。这是因为与常规行为相反,如果未找到符合该条件的结果,则不会根据我的测试执行 2 个方法的参数数组的合并。