如果我尝试声明一个属性,如下所示:
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();
});
}
更新/免责声明
此代码有效,但它将覆盖常规的雄辩模型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");
});
}
}
Laravel 7, 8, 9, 10, and beyond(英语:
Laravel 7, 8, 9, 10, and beyond
)如果要在从模型中检索属性值时设置默认值,
将以下内容添加到模型中:
protected static function booted()
{
static::retrieved(function ($self) {
$self->your_column ??= 'default_value';
});
}
如果要设置创建值,只需将retrieved
更改为creating