[英]How to set a default attribute value for a Laravel / Eloquent model?
如果我尝试声明一个属性,如下所示:
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 线程。
这就是我现在正在做的事情:
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,
);
此处讨论了该问题。
我知道这真的很老了,但我刚刚遇到了这个问题,并且能够使用这个网站解决这个问题。
将此代码添加到您的模型
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->user_id = auth()->id();
});
}
更新/免责声明
此代码有效,但它将覆盖常规 Eloquent 模型creating
事件
在构造函数中设置属性值:
public function __construct()
{
$this->attributes['locale'] = App::currentLocale();
}
我将它用于 Laravel 8(静态和动态更改属性)
<?php
namespace App\Models\Api;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
protected static function defAttr($messages, $attribute){
if(isset($messages[$attribute])){
return $messages[$attribute];
}
$attributes = [
"password" => "123",
"created_at" => gmdate("Y-m-d H:i:s"),
];
return $attributes[$attribute];
}
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::creating(function ($messages) {
$messages->password = self::defAttr($messages, "password");
$messages->created_at = self::defAttr($messages, "created_at");
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.