我有几个共享一些通用功能(由于它们的多态性)的模型,我想将它们放入 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
}
我正在寻找一种干净的方法来做到这一点,这样子类就不会因为我在层次结构中插入一个额外的类来收集公共(public)代码而过度改变。
最佳答案
不知道这是否有效...
class Photo extends ResourceContentModel
{
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->with = array_merge(['someRelationship'], parent::$this->with);
}
}
或者也许在 ResourceContentModel 上添加一个方法来访问该属性。
class ResourceContentModel extends Model
{
public function getParentWith()
{
return $this->with;
}
}
然后
class Photo extends ResourceContentModel
{
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->with = array_merge(['someRelationship'], parent::getParentWith());
}
}
编辑
在第三个代码片段的构造函数中,
$this->with = array_merge(['someRelationship'],parent->getParentWith());
需要
$this->with = array_merge(['someRelationship'],parent::getParentWith());
关于laravel 5如何添加到子模型类中的$with/$appends字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44601731/