创建动态Laravel访问器

Den*_*ebe 5 php laravel laravel-5.5

我有一个Product模型,也有一个Attribute模型.Product和之间的关系Attribute很多.在我的Product模型上,我正在尝试创建一个动态访问器.我熟悉Laravel的访问器和mutator功能,如此处所述.我遇到的问题是每次创建产品属性时我都不想创建访问器.

例如,产品可能具有颜色属性,可以这样设置:

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

然后可以像这样访问产品的颜色$product->color.如果我在产品中添加size属性,我需要在Product模型上设置另一个访问者,以便我可以像这样访问它$product->size.

有没有办法设置一个"动态"访问器来处理作为属性访问时的所有属性?

我是否需要使用自己的覆盖Laravel的访问器功能?

Lar*_*leg 5

是的,您可以将自己的逻辑添加到 Eloquent Model 类的 getAttribute() 函数中(在模型中覆盖它),但在我看来,这不是一个好的做法。

也许你可以有一个功能:

public function getProductAttr($name)
{
    foreach ($this->productAttributes as $attribute) {
        if ($attribute->code === $name) {
            return $attribute->pivot->value;
        }
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

并这样称呼它:

$model->getProductAttr('color');
Run Code Online (Sandbox Code Playgroud)


Abi*_*aza 5

覆盖 Magic 方法 - __get()方法。

尝试这个。

public function __get($key)
{
    foreach ($this->productAttributes as $attribute) {
        if ($attribute->code === $key) {
            return $attribute->pivot->value;
        }
    }

    return parent::__get($key);
}
Run Code Online (Sandbox Code Playgroud)