我有几个模型共享某些通用功能(由于它们的多态性),我希望将它们提取到一个ResourceContentModel类(或甚至是特征)中。
ResourceContentModel类将扩展eloquent Model类,然后我的各个模型将扩展ResourceContentModel。
我的问题在于模型字段,如$with、$appends和$touches。如果我在ResourceContentModel中使用它们来实现任何通用功能,那么当我在子模型类中重新定义它们时,它会覆盖我在父类中设置的值。
寻找一些干净的方法来解决这个问题?
例如:
class ResourceContentModel extends Model
{
protected $with = ['resource']
protected $appends = ['visibility']
public function resource()
{
return $this->morphOne(Resource::class, 'content');
}
public function getVisibilityAttribute()
{
return $this->resource->getPermissionScope(Permission::RESOURCE_VIEW);
}
}
class Photo extends ResourceContentModel
{
protected $with = ['someRelationship']
protected $appends = ['some_other_property']
THESE ARE A PROBLEM AS I LOSE THE VALUES IN ResourceContentModel
}
我希望以简洁的方式完成这个任务,使得子类不会因为我在继承结构中增加了一个额外的类来收集公共代码而过度改变。
$appends
,请查看https://laracasts.com/discuss/channels/general-discussion/define-model-attributes-in-trait/replies/50522;对于`$with`,您可以尝试查看https://laravel.com/docs/5.6/eloquent#global-scopes。 - ctf0