Laravel在setAttribute中获取模型ID [英] Laravel get model id inside setAttribute
本文介绍了Laravel在setAttribute中获取模型ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的模型,我想在SetFooAttribute中获取属性.但是所有时候$ this-> getAttribute('id')都是空的!有没有办法访问ID?
I have model like this where i want to get a attribute inside SetFooAttribute. but all time $this->getAttribute('id') is empty! is there a way to access id ?
class MyModel extends Model
{
public static function boot()
{
parent::boot();
static::created(function($model)
{
$model->uuid = Uuid::generate(4)->string;
$model->save();
});
}
public function setFooAttribute($value)
{
$this->attributes['foo'] = $value.'-'.$this->getAttribute('id');
}
推荐答案
您应使用 getKey()方法来获取模型主键的值.像$this->getKey()
You should use getKey() method to get the value of the model's primary key. Use it like $this->getKey()
这篇关于Laravel在setAttribute中获取模型ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文