创建动态的Laravel访问器 [英] Create dynamic Laravel accessor
问题描述
我有一个Product
模型,也有一个Attribute
模型. Product
和Attribute
之间的关系是多对多的.在我的Product
模型上,我试图创建一个动态访问器.我熟悉此处中所述的Laravel的访问器和更改器功能.我遇到的问题是,我不想在每次创建产品属性时都创建访问器.
I have a Product
model and also an Attribute
model. The relationship between Product
and Attribute
is many to many. On my Product
model I am trying to create a dynamic accessor. I am familiar with Laravel's accessors and mutators feature as documented here. The problem I am having is that I do not want to create an accessor every time I create a product attribute.
例如,某产品可能具有可以这样设置的颜色属性:
For example, A product may have a color attribute which could be setup like so:
/**
* 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
那样访问该访问器.
The product's color could then be accessed like so $product->color
.
If I where to add a size
attribute to the product I would need to setup another accessor on the Product
model so I could access that like so $product->size
.
有没有一种方法可以设置单个动态"访问器来处理作为属性访问的所有属性?
我是否需要使用自己的功能覆盖Laravel的访问器功能?
推荐答案
是的,您可以将自己的逻辑添加到Eloquent Model类的getAttribute()函数中(在模型中覆盖它),但是我认为,这不是一个好习惯.
Yes, you can add your own piece of logic into the getAttribute() function of the Eloquent Model class (override it in your model), but in my opinion, it's not a good practice.
也许您可以拥有一个功能:
Maybe you can have a function:
public function getProductAttr($name)
{
foreach ($this->productAttributes as $attribute) {
if ($attribute->code === $name) {
return $attribute->pivot->value;
}
}
return null;
}
并这样称呼它:
$model->getProductAttr('color');
这篇关于创建动态的Laravel访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!