問題描述
如果我嘗試聲明一個屬性,如下所示:
public $quantity = 9;
...它不起作用,因為它不被視為屬性",而只是模型類的屬性.不僅如此,我還阻止了對實際真實存在的數量"屬性的訪問.
那我該怎么辦?
這就是我現在正在做的:
protected $defaults = array('數量' =>9、);公共函數 __construct(array $attributes = array()){$this->setRawAttributes($this->defaults, true);parent::__construct($attributes);}
我建議將此作為 PR,因此我們不需要在每個模型中都聲明此構造函數,并且只需在我們的模型中聲明 $defaults
數組即可輕松應用...><小時>
更新:
正如 cmfolio 所指出的,實際的答案很簡單:
只需覆蓋 $attributes
屬性即可!像這樣:
protected $attributes = array('數量' =>9、);
在此處討論了該問題.
If I try declaring a property, like this:
public $quantity = 9;
...it doesn't work, because it is not considered an "attribute", but merely a property of the model class. Not only this, but also I am blocking access to the actually real and existent "quantity" attribute.
What should I do, then?
This is what I'm doing now:
protected $defaults = array(
'quantity' => 9,
);
public function __construct(array $attributes = array())
{
$this->setRawAttributes($this->defaults, true);
parent::__construct($attributes);
}
I will suggest this as a PR so we don't need to declare this constructor at every Model, and can easily apply by simply declaring the $defaults
array in our models...
UPDATE:
As pointed by cmfolio, the actual ANSWER is quite simple:
Just override the $attributes
property! Like this:
protected $attributes = array(
'quantity' => 9,
);
The issue was discussed here.
這篇關于如何為 Laravel/Eloquent 模型設置默認屬性值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!