当我尝试使用eloquent进行更新时,我收到此消息“无法更新标识列'id'”错误。
使用Laravel 5.2
$m = new ModelName;
$m->name = 'Test model insert';
$m->save();
$m1 = ModelName::find( $m->id );
if ($m1) {
$m1->name = 'Test model update';
$m1->save(); // Error occured here.
}
答案 0 :(得分:1)
您可以使用
trait WithoutUpdateId
{
/**
* Perform a model update operation.
*
* @param \Illuminate\Database\Eloquent\Builder $query
*
* @return bool
*/
protected function performUpdate(Builder $query)
{
// If the updating event returns false, we will cancel the update operation so
// developers can hook Validation systems into their models and cancel this
// operation if the model does not pass validation. Otherwise, we update.
if ($this->fireModelEvent('updating') === false) {
return false;
}
// First we need to create a fresh query instance and touch the creation and
// update timestamp on the model which are maintained by us for developer
// convenience. Then we will just continue saving the model instances.
if ($this->usesTimestamps()) {
$this->updateTimestamps();
}
// Once we have run the update operation, we will fire the "updated" event for
// this model instance. This will allow developers to hook into these after
// models are updated, giving them a chance to do any special processing.
$dirty = $this->getDirty();
if (count($dirty) > 0) {
unset($dirty['id']);
$this->setKeysForSaveQuery($query)->update($dirty);
$this->fireModelEvent('updated', false);
$this->syncChanges();
}
return true;
}
}
我已在此处删除了ID
unset($dirty['id']);
在模型类
中class ModelName extends Model
{
use WithoutUpdateId;
...
}
答案 1 :(得分:0)
我想到了我的问题。在调用$ m1-> save()之前,我确实取消了设置$ m1-> id。现在效果很好。