我有一种情况,我在模型上设置了一些自定义属性。数据库中不存在这些属性。在模型上使用->isDirty()
时,我获得了不属于数据库的自定义属性。
在保存模型之前是否有一些干净的方法来删除这些属性?
$model = SomeModel::find(1);
$model->database_attribute = 'I exists in the database';
$model->custom_not_in_database_attribute = 'I don\'t exists in the database';
$model->save(); // remove dirty on save?!
我当然可以解雇他们unset($model->custom_not_in_database_attribute)
,但我想知道是否有更清洁的方法来做到这一点?
像(不存在)$model->saveOriginalOnly()
的东西
您可以像这样使用getAttributes()和getOriginal():
$model=Model::findOrFail($id);
$model->new='new';
foreach ($model->getAttributes() as $key => $value) {
if(!in_array($key, array_keys($model->getOriginal())))
unset($model->$key);
}
dd($model);
对我来说,完整的解决方案是将此方法添加到自定义基本模型中。它保存了原始字段。但保留自定义属性。
public function saveOriginalOnly()
{
$dirty = $this->getDirty();
foreach ($this->getAttributes() as $key => $value) {
if(!in_array($key, array_keys($this->getOriginal()))) unset($this->$key);
}
$isSaved = $this->save();
foreach($dirty as $key => $value) {
$this->setAttribute($key, $value);
}
return $isSaved;
}