gpt4 book ai didi

laravel - 修改 Laravel 模型的所有属性

转载 作者:行者123 更新时间:2023-12-02 14:11:56 26 4
gpt4 key购买 nike

访问器将在单个属性上完美地完成其工作,但我需要一种方法来自动对所有属性执行访问器/Getter 工作。

目的是我想在获取属性时替换一些字符/数字,然后将它们打印出来。我可以在 Controller 内手动完成此操作,但我认为从模型端自动完成它会很棒。

就像覆盖 getAttributes() 方法:

public function getAttributes()
{
foreach ($this->attributes as $key => $value) {
$this->attributes[$key] = str_replace([...], [...], $value);
}
return $this->attributes;
}

但我每次都必须在模型上调用它 $model->getAttributes();

有什么方法可以自动完成并干燥吗?

最佳答案

尝试如下:

public function getAttribute($key)
{
if (array_key_exists($key, $this->attributes) || $this->hasGetMutator($key)) {
if($key === 'name') return 'modify this value';
return $this->getAttributeValue($key);
}

return $this->getRelationValue($key);
}

它完全覆盖默认方法,所以要小心。

编辑

另请查看:http://laravel.com/docs/5.1/eloquent-mutators

关于laravel - 修改 Laravel 模型的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33976777/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com