繁体   English   中英

Laravel 具有多态关系的全局访问

[英]Laravel global access with polymorphic relations

在我的应用程序中,几乎每个表中都有两列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方法成为全局方法,而不是在每个 model class 中添加。

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

你可以制作一个特征并在每个 model 需要这个 function 中使用它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM