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

时间:2013-09-11 17:22:12

标签: php model laravel laravel-4 eloquent

如果我尝试声明属性,就像这样:

public $quantity = 9;

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

那我该怎么办?

4 个答案:

答案 0 :(得分:74)

对此的更新...

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

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

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

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

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

答案 1 :(得分:51)

这就是我现在正在做的事情:

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,
);

讨论了这个问题here

答案 2 :(得分:0)

我知道这确实很老,但是我遇到了这个问题,并且能够使用this site解决此问题。

将此代码添加到模型中

protected static function boot()
{
   parent::boot();

   static::creating(function ($model) {
        $model->user_id = auth()->id();
    });
}

更新/免责声明

此代码有效,但是它将覆盖常规的口才模型creating事件

答案 3 :(得分:0)

设置属性值和构造

  public function __construct()
    {
        $this->attributes['locale'] = App::currentLocale();
    }