获取模型和清除属性

时间:2017-10-08 08:41:33

标签: php laravel eloquent

如何获取模型然后一次清除其属性,以便其所有属性都变为null

有这方法吗?

例如:

$model = Model::findOrFail(1);
$model->clearAttributes();

2 个答案:

答案 0 :(得分:0)

想出了这个:

public $protected_schema = ['id', 'created_at', 'updated_at'];

public function clearAttributes()
{
    foreach (Schema::getColumnListing($this->getTable()) as $name) {
        if (!in_array($name, $this->protected_schema)) {
            $this->{$name} = null;
        }
    }
}

咩。

答案 1 :(得分:0)

你可以这样做:

$model = Model::findOrFail(1);
$model->fill(array_fill_keys($model->getFillable(), null));

getFillable()会为您提供可填充属性列表,array_fill_keys()会创建一个包含这些键的数组,并null作为值。

如果您想在此之后将模型保存到数据库,只需执行$model->save();

相关问题