我有一个包含自定义属性的模型
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)
这不起作用,这是正确的方法吗?
问题是你的访问器总是返回 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”。
归档时间: |
|
查看次数: |
29561 次 |
最近记录: |