2017-10-08 45 views
0

我將如何獲取模型,然後一次清除其屬性,以使其所有屬性都變爲null獲取模型並清除屬性

有沒有這樣的方法?

例如:

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

回答

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

咩。

0

你可以做這樣的事情:

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

getFillable()會給你可填寫屬性的列表和array_fill_keys()將創建與數組中的鍵和null作爲值。

如果您想將模型保存到數據庫之後,只需執行$model->save();