問題描述
我有一個自定義的 setter,我在我的模型的 __construct
方法中運行它.
I have a custom setter that I'm running in a __construct
method on my model.
這是我要設置的屬性.
protected $directory;
我的構造函數
public function __construct()
{
$this->directory = $this->setDirectory();
}
二傳手:
public function setDirectory()
{
if(!is_null($this->student_id)){
return $this->student_id;
}else{
return 'applicant_' . $this->applicant_id;
}
}
我的問題是在我的 setter 中,$this->student_id
(這是從數據庫中提取的模型的一個屬性)返回 null
.當我在我的 setter 中 dd($this)
時,我注意到我的 #attributes:[]
是一個空數組.
所以,直到 __construct()
被觸發后,模型的屬性才會被設置.如何在構造方法中設置 $directory
屬性?
My problem is that inside my setter the, $this->student_id
(which is an attribute of the model being pulled from the database) is returning null
.
When I dd($this)
from inside my setter, I notice that my #attributes:[]
is an empty array.
So, a model's attributes aren't set until after __construct()
is fired. How can I set my $directory
attribute in my construct method?
推薦答案
您需要將構造函數更改為:
You need to change your constructor to:
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
$this->directory = $this->setDirectory();
}
第一行 (parent::__construct()
) 會在你的代碼運行之前運行 Eloquent Model
自己的構造方法,這將設置所有的屬性為你.此外,對構造函數方法簽名的更改是繼續支持 Laravel 期望的用法: $model = new Post(['id' => 5, 'title' => 'My Post']);代碼>
The first line (parent::__construct()
) will run the Eloquent Model
's own construct method before your code runs, which will set up all the attributes for you. Also the change to the constructor's method signature is to continue supporting the usage that Laravel expects: $model = new Post(['id' => 5, 'title' => 'My Post']);
經驗法則實際上是始終記住,在擴展類時,要檢查您沒有覆蓋現有方法以使其不再運行(這對于神奇的 __construct
、__get
等方法).您可以檢查原始文件的來源,看看它是否包含您正在定義的方法.
The rule of thumb really is to always remember, when extending a class, to check that you're not overriding an existing method so that it no longer runs (this is especially important with the magic __construct
, __get
, etc. methods). You can check the source of the original file to see if it includes the method you're defining.
這篇關于Eloquent Laravel 模型上的 __construct的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!