如何设置Laravel / Eloquent模型的默认属性值? [英] How to set a default attribute value for a Laravel / Eloquent model?

查看:1443
本文介绍了如何设置Laravel / Eloquent模型的默认属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试声明属性,如下所示:

If I try declaring a property, like this:

public $quantity = 9;

...它不起作用,因为它不被认为是属性,而只是模型类的属性。不仅如此,我也阻止访问实际上真实存在的数量属性。

...it doesn't work, because it is not considered an "attribute", but merely a property of the model class. Not only this, but also I am blocking access to the actually real and existent "quantity" attribute.

那么我应该怎么办?

推荐答案

这是我现在在做的:

protected $defaults = array(
   'quantity' => 9,
);

public function __construct(array $attributes = array())
{
    $this->setRawAttributes($this->defaults, true);
    parent::__construct($attributes);
}

我会建议这是公关,所以我们不需要声明这个每个模型的构造函数,并且可以通过在我们的模型中简单地声明 $ defaults 数组来轻松应用...

I will suggest this as a PR so we don't need to declare this constructor at every Model, and can easily apply by simply declaring the $defaults array in our models...

更新

如cmfolio所示,实际的回答很简单

As pointed by cmfolio, the actual ANSWER is quite simple:

只需覆盖 $ attributes 属性!像这样:

Just override the $attributes property! Like this:

protected $attributes = array(
   'quantity' => 9,
);

这个问题在这里讨论: https://github.com/laravel/framework/issues/2265

The issue was dicussed here: https://github.com/laravel/framework/issues/2265

这篇关于如何设置Laravel / Eloquent模型的默认属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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