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

标签 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
}

我正在寻找一种干净的方法来做到这一点,这样子类就不会因为我在层次结构中插入一个额外的类来收集公共(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/

相关文章:

php - Laravel 5 中的单例类

php - Laravel Blade - @slot/@component 与 @include 的优势?

php - laravel 5.4 MIME 自定义错误消息不起作用?

php - 向 Blade 中的日期字段添加三个小时

javascript - 如何将复选框中的值传递给 Laravel Controller

laravel - 什么是工匠迁移 :install use for?

LaravelLocalization.php 中的 Laravel 5 UnsupportedLocaleException

php - Laravel dompdf 错误 "Image not found or type unknown"

laravel - 存储::移动给 "File not found at path:"Laravel 与 Ubuntu

php - 如何修复laravel迁移中的外键错误