【问题标题】:Laravel: Accessing model attributes in the constructor methodLaravel:在构造函数方法中访问模型属性
【发布时间】:2019-10-15 23:41:51
【问题描述】:

如何在 laravel eloquent 上使用 __construct 并获取属性。我累了:

public function __construct() {
    parent::__construct();
    dd($this->attributes);
}

我的代码返回 null。但是在抽象类Model 上填充了所有属性:

public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->initializeTraits();

    $this->syncOriginal();

    $this->fill($attributes);
}

可以在构造方法中获取模型属性吗?

【问题讨论】:

    标签: laravel eloquent laravel-5.8


    【解决方案1】:

    试试accessors

    https://laravel.com/docs/5.8/eloquent-mutators#accessors-and-mutators

    定义如下:

    public function getFirstNameAttribute($value)
    {
         return ucfirst($value);
    }
    

    然后使用$this->first_name类似这样的东西。

    【讨论】:

    • 我需要访问__constructor() 方法中的属性。这对我不起作用! @Vikash Pathak
    • @AndreasHunter 你能补充一下你为什么需要这个吗?
    • 我有 3 种帖子类型。 Post 模型默认有 3 个字段 titledescriptiontype。我必须在请求时将自定义属性附加到 $attributes 数组检查帖子类型。每种帖子类型都有不同的属性。为了检测请求的帖子类型,我必须使用__construct() 方法,然后使用所需的属性生成所需的结果@Vikash Pathak
    • @Andress 为什么不创建find() 的包装函数并在那里检查所有客户状况。您可以在所有地方使用它。
    【解决方案2】:

    我通过像这样更新构造函数在本地对此进行了测试:

    public function __construct(array $attributes = []) {
        parent::__construct($attributes);
        dd($this->getAttributes());
    }
    

    但是,我发现当从数据库中获取对象时,它的属性并没有填充到构造函数中,因此不可能在那里访问它们。

    你可以做的是在对象初始化后访问属性:

    $post = Post::find(1);
    dump($post->getAttributes());
    

    不确定这是否有帮助,但确实如此。

    也许事件或观察者可以帮助您满足您的需求: https://laravel.com/docs/5.8/eloquent#events
    https://laravel.com/docs/5.8/eloquent#observers

    【讨论】:

    • 返回空array
    • 我厌倦了你更新的代码然后再次返回空array@GTCrais
    • 你是如何制作你的对象的?
    • 很简单:$post = Post::find(1);@GTCrais
    • @AndreasHunter 我已经在本地进行了测试,实际上它不起作用。我再次更新了我的答案。
    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 2023-04-02
    • 2020-10-17
    • 2016-08-13
    • 2018-09-24
    • 2012-07-06
    • 2018-01-13
    • 2019-05-21
    相关资源
    最近更新 更多