如何使用不在数据库中的自定义属性保存模型? - Laravel 5.4

问题描述 投票:2回答:2

我有一种情况,我在模型上设置了一些自定义属性。数据库中不存在这些属性。在模型上使用->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()的东西

php laravel laravel-5.4
2个回答
3
投票

您可以像这样使用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);

2
投票

对我来说,完整的解决方案是将此方法添加到自定义基本模型中。它保存了原始字段。但保留自定义属性。

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;
}

另见:https://codeneverlied.com/how-to-save-a-model-with-custom-attributes-that-are-not-in-the-database-laravel-5-4/

© www.soinside.com 2019 - 2024. All rights reserved.