laravel 修改 Eloquent 模型的自定义属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43756564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:54:18  来源:igfitidea点击:

Modify a custom attribute of an Eloquent Model

laraveleloquent

提问by Lucian P.

I have a model which contain a custom attribute

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

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

I need to change the value of the custom attribute, like:

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

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

This does not work, which is the correct way to do it?

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

采纳答案by LombaX

The problem is that your accessor returns always 1

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

public function getCounterAttribute()
{
    return 1;
}

Your loop sets correctly the counterattribute (inspectable via $model->attributes['counter']). However, when you call $test->counterits value is resolved via the getCounterAttribute()method, that returns always 1.

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

Update your getCounterAttribute()to something like this:

将您更新getCounterAttribute()为这样的内容:

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

this way, you are saying: "if the counter attribute is set, return it. Otherwise, return 1".

这样,您就是说:“如果设置了计数器属性,则返回它。否则,返回 1”。

回答by René

You'll need to define a mutator on your Test model:

你需要在你的测试模型上定义一个mutator:

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

For more info: https://laravel.com/docs/5.4/eloquent-mutators#defining-a-mutator

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