如果至少有一个字段已更改,如何更新行 - 并返回laravel 5.7中的所有更改?

问题描述 投票:0回答:1

我正在关注这个post,以便在任何字段发生变化时更新一行。

//Retrieve an array from an API
$fields = ['field1'=>var1, 'field2'=>var2, ...];

$row = MyModel::ofField1($this->field1)->ofField2($fields['field2'])->first(); //Selects the row under field1 AND field2 condition. It is working.
$row->updateOrCreate($fields);//Should assign the new values to the model (but not persist)

//Next line should compare the model with what we have in the
//database. At least 1 value from the incomming array is different from what 
//we have in the database - so Update the row with the new value.
if($row->isDirty()){
   $row->save();
}

这不起作用,我错过了什么?

laravel-5 eloquent insert-update
1个回答
0
投票

->updateOrCreate()将保留数据(你提到过你不想这样做)。

这个方法有两个参数:

  • 一个用于查询具有某些字段值的行
  • 另一个用于更新/创建记录的数据

在这种情况下,如果您只是检查两个字段中的一个是否已更新,则应检查是否已使用->isDirty($field)更新了特定字段:

$row = MyModel::first();

if ($row->isDirty('field1')) {
    $row->field1 = $fields['field1'];
}

if ($row->isDirty('field2')) {
    $row->field2 = $fields['field2'];
}

$row->save();

由于你可能有许多从api返回的字段,你可以循环检查:

$row = MyModel::first();

foreach ($fields as $field => $value) {
    if ($row->isDirty($field)) {
        $row->$field = $value;
    }
}

$row->save();
© www.soinside.com 2019 - 2024. All rights reserved.