保存模型时忽略突变器


Mutators ignored when model saved

>我有一个模型,它将小数存储为整数,当使用突变器从数据库中读取/写入时,应该转换这些整数:

public function getPrice($value)
{
    return $value / 100;
}
public function setPrice($value)
{
    $this->attributes['price'] = round($value, 2) * 100;
}

但是,突变器永远不会被调用。

例如,如果我做create/insert/save等:

PriceHistory::create(['price' => 1234.25]);

我收到此错误:

Illuminate'Database'QueryException with message 'SQLSTATE[22P02]:
    Invalid text representation: 7 ERROR:
        invalid input syntax for integer:
            "1234.25" (SQL: insert into "price_history" ("price") values (1234.25))'

我在这里做错了什么?

来自文档:

定义访问器

若要定义访问器,请在模型上创建 getFoo属性方法 其中 Foo 是您要访问的列的"骆驼"大小写名称。

所以,它会是这样的:

public function getPriceAttribute($value)
{
    return $value / 100;
}
public function setPriceAttribute($value)
{
    $this->attributes['price'] = round($value, 2) * 100;
}

访问器/突变器的名称需要包含Attribute,就像文档一样。试一试:

public function getPriceAttribute($value)
{
    return $value / 100;
}
public function setPriceAttribute($value)
{
    $this->attributes['price'] = round($value, 2) * 100;
}