A __construct on an Eloquent Laravel Model(Eloquent Laravel 模型上的 __construct)
问题描述
我有一个自定义的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Eloquent Laravel 模型上的 __construct
基础教程推荐
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 使用 PDO 转义列名 2021-01-01