修改Eloquent模型的自定义属性

时间:2017-05-03 09:45:43

标签: laravel eloquent

我有一个包含自定义属性的模型

class Test extends Model
{
    protected $appends = ['counter'];
    public function getCounterAttribute()
    {
        return 1;
    }
}

我需要更改自定义属性的值,例如:

$tests = Test::all();
foreach ($tests AS $test) {
    $test->counter = $test->counter + 100;
}

这不起作用,这是正确的方法吗?

2 个答案:

答案 0 :(得分:1)

问题是你的访问者总是返回1

public function getCounterAttribute()
{
    return 1;
}

您的循环正确设置counter属性(可通过$model->attributes['counter']检查)。 但是,当您致电$test->counter时,其价值会通过getCounterAttribute()方法解决,该值始终为1。

将您的getCounterAttribute()更新为以下内容:

public function getCounterAttribute()
{
    return isset($this->attributes['counter']) ? $this->attributes['counter'] : 1;
}

这样,你说:“如果设置了counter属性,则返回它。否则,返回1”。

答案 1 :(得分:0)

您需要在Test模型上定义一个mutator:

public function setCounterAttribute($value)
{
    $this->attributes['counter'] = value;
}

了解更多信息:https://laravel.com/docs/5.4/eloquent-mutators#defining-a-mutator

相关问题