gpt4 book ai didi

php - 如何为 Laravel/Eloquent 模型设置默认属性值?

转载 作者:IT王子 更新时间:2023-10-29 00:51:47 25 4
gpt4 key购买 nike

如果我尝试像这样声明一个属性:

public $quantity = 9;

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

那我该怎么办呢?

最佳答案

对此的更新...

@j-bruni 提交了一个提案,Laravel 4.0.x 现在支持使用以下内容:

protected $attributes = array(
'subject' => 'A Post'
);

它会在您构建时自动将您的属性 subject 设置为 A Post。您不需要使用他在回答中提到的自定义构造函数。

但是,如果你最终使用了像他一样的构造函数(我需要这样做才能使用 Carbon::now()),请注意 $this-> setRawAttributes() 将覆盖您使用上面的 $attributes 数组设置的任何内容。例如:

protected $attributes = array(
'subject' => 'A Post'
);

public function __construct(array $attributes = array())
{
$this->setRawAttributes(array(
'end_date' => Carbon::now()->addDays(10)
), true);
parent::__construct($attributes);
}

// Values after calling `new ModelName`

$model->subject; // null
$model->end_date; // Carbon date object

// To fix, be sure to `array_merge` previous values
public function __construct(array $attributes = array())
{
$this->setRawAttributes(array_merge($this->attributes, array(
'end_date' => Carbon::now()->addDays(10)
)), true);
parent::__construct($attributes);
}

Github thread了解更多信息。

关于php - 如何为 Laravel/Eloquent 模型设置默认属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18747500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com