我遇到了在模型上设置一些自定义属性的情况。这些属性在数据库中不存在。在模型上使用->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);
关于php - 如何使用数据库中没有的自定义属性保存模型? -Laravel 5.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45028496/