我正在关注这个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();
}
这不起作用,我错过了什么?
->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();