修改 Eloquent 模型的自定义属性

Luc*_* P. 4 laravel eloquent

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

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

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

$tests = Test::all();
foreach ($tests AS $test) {
    $test->counter = $test->counter + 100;
}
Run Code Online (Sandbox Code Playgroud)

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

Lom*_*baX 6

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

public function getCounterAttribute()
{
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

您的循环正确设置了counter属性(可通过检查$model->attributes['counter'])。然而,当你调用$test->counter它的值是通过该getCounterAttribute()方法解析时,它总是返回 1。

将您的更新getCounterAttribute()为如下所示:

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

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