Eloquent Laravel 模型上的 __construct [英] A __construct on an Eloquent Laravel Model

查看:28
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆