2017-04-05 35 views
0

我在編寫模型時是否可以創建或設置屬性。我試着用setMutator做到這一點,但是當沒有在列表中提供的參數屬性保存的值不會產生Laravel在模型中寫入時創建動態屬性

public function setExampleAttribute($value) 
{ 
    $this->attributes['example'] = 100; 
} 

所以,當我這樣做:

Version::create(['name' => 'mark', 'example' => '50'); 

的記錄保存100

但是當我這樣做:

Version::create(['name' => 'mark'); 

的記錄是空的。

有辦法在兩者之間做點什麼嗎?所以在寫對象之前,添加一些動態內容?

回答

0

它不起作用,因爲create()使用fill()來設置屬性值。你可以嘗試使用$attributes設置默認值:

protected $attributes = ['example' => 100]; 

如果你想添加一個動態屬性,你可以使用Eloquent creating event在其內部設置屬性:

$this->attributes['example'] = $value; 

或致電突變:

$this->setExampleAttribute(null); 
+0

我想讓它變成動態的,這取決於所提供的情況和其他變量。硬編碼不是這裏的選項。 – Erhnam

+0

@Erhnam我已經更新了答案。 –