[英]Laravel global access with polymorphic relations
In my application I have two columns employable_id
&& employable_type
in almost every table, which are used for storing the information about the user who has created the record.在我的应用程序中,几乎每个表中都有两列employable_id
&& employable_type
,用于存储有关创建记录的用户的信息。
Something like this:像这样:
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...
Subscriber.php订户.php
class Subscriber extends Model
{
/**
* Polymorphic relations
*/
public function employable()
{
return $this->morphTo();
}
}
I have created an accessor
to combine polymorphic relationship's columns, which is working fine.我创建了一个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 . ' ]';
}
}
I am trying to make the getAddedByAttribute
method global instead of adding in every model class.我试图使getAddedByAttribute
方法成为全局方法,而不是在每个 model class 中添加。
How can I do that..?我怎样才能做到这一点..?
you can make a trait and use it in every model need this function你可以制作一个特征并在每个 model 需要这个 function 中使用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.