0

在我的应用程序中,几乎每个表都有两列employable_id&& employable_type,用于存储有关创建记录的用户的信息。

像这样的东西:

subscribers:                          products:
------------------------------------  ------------------------------------
id | employable_id | employable_type  id | employable_id | employable_type
------------------------------------  ------------------------------------
 1 |             1 | App\Company       1 |             1 | App\Company
 2 |             1 | App\Company       2 |             1 | App\Employee
 3 |             1 | App\Employee      3 |             3 | App\Employee
 4 |             1 | App\Employee      4 |             8 | App\Employee     and more...

订阅者.php

class Subscriber extends Model
{
    /**
     * Polymorphic relations
     */
    public function employable()
    {
        return $this->morphTo();
    }
}

我创建了一个accessor组合多态关系的列,它工作正常。

class Subscriber extends Model
{
    /**
     * Polymorphic relations
     */
    public function employable()
    {
        return $this->morphTo();
    }

    /**
     * Accessor
     */
    public function getAddedByAttribute()
    {
        return $this->employable->name . ' [ ' . $this->employable->designation . ' ]';
    }
}
class Product extends Model
{
    /**
     * Polymorphic relations
     */
    public function employable()
    {
        return $this->morphTo();
    }

    /**
     * Accessor
     */
    public function getAddedByAttribute()
    {
        return $this->employable->name . ' [ ' . $this->employable->designation . ' ]';
    }
}

我正在尝试使该getAddedByAttribute方法全局化,而不是添加到每个模型类中。

我怎样才能做到这一点..?

4

1 回答 1

1

您可以制作一个特征并在每个需要此功能的模型中使用它

于 2020-12-01T18:49:29.580 回答