Laravel/Mysql:无法将字段设置为 null

问题描述

我正在处理一个 Laravel 项目并尝试在 MysqL db 中复制一条记录。 复制后,我想将字段值设置为 null(appointment_status)。 一切正常,除了新记录的值 (appointment_status) 与原始记录相同,即使我将其设置为 null。

    $newAppointment = $appointment->replicate();
    //push to get the id for the cloned record
    $newAppointment->push();
    $newAppointment->duplicated_from_id = $appointment->id;
    $newAppointment->appointment_status = null;
    $newAppointment->save();
    //updating the old appointment
    $appointment->duplicated_to_id = $newAppointment->id;
    $appointment->save();

解决方法

代替整个代码块,试试这样的:

// replicate as the new record with some different fields
$newAppointment = $appointment->replicate()->fill([
    'duplicated_from_id' => $appointment->id,'appointment_status' => null,])->save();

// update some fields of initial original record
$appointment->update([
    'duplicated_to_id' => $newAppointment->id,]);

更多信息请查看this