创建动态 Laravel 访问器

Create dynamic Laravel accessor

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

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

/**
 * 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.

有没有一种方法可以设置一个 "dynamic" 访问器来处理我作为 属性 访问时的所有属性?

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

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

也许你可以有一个功能:

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

    return null;
}

并这样称呼它:

$model->getProductAttr('color');

覆盖魔术方法 - __get() 方法。

试试这个。

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

    return parent::__get($key);
}

我认为 Олег Шовкун 的答案可能是正确的,但如果您确实想使用模型属性表示法,则可以通过 class 变量将所需的参数输入到模型中。

class YourModel extends Model{

  public $code;

  public function getProductAttribute()
  {
    //a more eloquent way to get the required attribute
    if($attribute = $this->productAttributes->filter(function($attribute){
       return $attribute->code = $this->code;
    })->first()){
        return $attribute->pivot->value;
    }

    return null;
  }
}

然后做

$model->code = 'color';
echo $model->product;

但是有点长而且没有意义