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

查看:838
本文介绍了雄辩的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;
        }
    }

我的问题是,在我的设置器中,$this->student_id(这是从数据库中提取模型的属性)正在返回null. 当我从设置器内部进入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.

这篇关于雄辩的Laravel模型的__construct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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