Tim*_*Uum 6 php laravel laravel-5.4
我有一种情况,我在模型上设置了一些自定义属性。这些属性在数据库中不存在。在->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?!
Run Code Online (Sandbox Code Playgroud)
我当然可以取消设置它们unset($model->custom_not_in_database_attribute),但我想知道是否有更干净的方法来做到这一点?
类似的东西(不存在) $model->saveOriginalOnly()
一种更简单的方法是将此属性添加为模型的属性,如下所示:
class Land extends Eloquent {
public $thisFieldWontBeSavedInDatabase;
//...
}
Run Code Online (Sandbox Code Playgroud)
一切都完成了。
通过这个简单的声明,eloquent 不会触发 __set() 方法来添加到 $attributes 属性。并且只有 $attributes 属性中的字段保存在数据库中。
您可以像这样使用 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);
Run Code Online (Sandbox Code Playgroud)