【发布时间】:2017-02-16 03:58:25
【问题描述】:
如何在 Laravel 模型上设置属性的默认值?
我应该在创建迁移时设置默认值还是应该在模型类中设置它?
【问题讨论】:
如何在 Laravel 模型上设置属性的默认值?
我应该在创建迁移时设置默认值还是应该在模型类中设置它?
【问题讨论】:
你也可以在模型中设置默认属性>
protected $attributes = [
'status' => self::STATUS_UNCONFIRMED,
'role_id' => self::ROLE_PUBLISHER,
];
您可以在这些链接中找到详细信息
1.) How to set a default attribute value for a Laravel / Eloquent model?
您也可以为此使用 Accessors & Mutators 您可以在 Laravel 文档中找到详细信息 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators
2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators
【讨论】:
empty or custom 的情况下设置默认值。像 public function setUserTypeAttribute($value){ $this->attributes['user_type'] = empty($value) ? 'User' : $value; } 我希望你能理解这个例子。
其他答案对我不起作用 - 它们可能已过时。这是我用作自动设置属性的解决方案:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
【讨论】:
你应该在migrations中设置默认值:
$table->tinyInteger('role')->default(1);
【讨论】:
new一个模型而不参考数据库