laravel 5 如何添加到 $with / $appends 子模型类中的字段

mad*_*adz 5 laravel laravel-5 laravel-5.4

我有几个模型共享一些通用功能(由于它们的多态性),我想将它们引入 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
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种干净的方法来做到这一点,这样子类就不会因为我在层次结构中插入一个额外的类来收集公共代码而过度改变。

小智 1

不知道这是否有效...

class Photo extends ResourceContentModel
{
    public function __construct($attributes = [])
    {
        parent::__construct($attributes);
        $this->with = array_merge(['someRelationship'], parent::$this->with);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者也许在 ResourceContentModel 上添加一个方法来访问该属性。

class ResourceContentModel extends Model
{
    public function getParentWith()
    {
        return $this->with;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后

class Photo extends ResourceContentModel
{
    public function __construct($attributes = [])
    {
        parent::__construct($attributes);
        $this->with = array_merge(['someRelationship'], parent::getParentWith());
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

在第三个片段的构造函数中,

$this->with = array_merge(['someRelationship'], parent->getParentWith());

需要是

$this->with = array_merge(['someRelationship'], parent::getParentWith());