我有一个Product
模型以及Attribute
模型。之间的关系Product
and Attribute
是多对多。在我的Product
模型 我正在尝试创建一个动态访问器。我熟悉 Laravel 的访问器和修改器功能(如文档所示)here https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators。我遇到的问题是我不想每次创建产品属性时都创建访问器。
例如,产品可能具有颜色属性,可以像这样设置:
/**
* Get the product's color.
*
* @param string $value
* @return string
*/
public function getColorAttribute($value)
{
foreach ($this->productAttributes as $attribute) {
if ($attribute->code === 'color') {
return $attribute->pivot->value;
}
}
return null;
}
然后可以像这样访问产品的颜色$product->color
。
如果我在哪里添加size
属性到产品我需要在Product
模型,这样我就可以像这样访问它$product->size
.
有没有办法可以设置一个“动态”访问器来处理作为属性访问时的所有属性?
我需要用我自己的访问器功能覆盖 Laravel 的访问器功能吗?
是的,您可以将自己的逻辑添加到 Eloquent Model 类的 getAttribute() 函数中(在模型中覆盖它),但在我看来,这不是一个好的做法。
也许你可以有一个功能:
public function getProductAttr($name)
{
foreach ($this->productAttributes as $attribute) {
if ($attribute->code === $name) {
return $attribute->pivot->value;
}
}
return null;
}
并这样称呼它:
$model->getProductAttr('color');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)