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

新手上路,请多包涵

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

 public $quantity = 9;

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

那我该怎么办?

原文由 J. Bruni 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 618
2 个回答

这就是我现在正在做的:

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

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

我会建议将其作为 PR,这样我们就不需要在每个模型中都声明此构造函数,并且只需在我们的模型中声明 $defaults 数组即可轻松应用…


更新

正如 cmfolio 所指出的, 实际的答案非常简单

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

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

这里 讨论了这个问题。

原文由 J. Bruni 发布,翻译遵循 CC BY-SA 4.0 许可协议

对此的更新…

@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 线程

原文由 cmfolio 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题