我有几个共享一些共同功能的模型(由于它们的多态性),我想将它们放入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
}
我正在采取一种干净的方式来实现这一目标,因为我已经在层次结构中的额外类中插入以收集公共代码,因此子类不会过度改变。
答案 0 :(得分:1)
不知道这是否有用......
public async static Task DeleteProjectFile(this Company companies)
{
var file = await GetCompanyFile(companies.CompanyName);
if (file == null)
{
var folder = await GlobalFolder();
file = await folder.CreateFileAsync(companies.CompanyName + GlobalFileExtension, CreationCollisionOption.ReplaceExisting);
}
Projects project = new Projects();
companies.ProjectsListed.Remove(project);
}
或者在ResourceContentModel上添加一个方法来访问该属性。
class Photo extends ResourceContentModel
{
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->with = array_merge(['someRelationship'], parent::$this->with);
}
}
然后
class ResourceContentModel extends Model
{
public function getParentWith()
{
return $this->with;
}
}
修改强>
在第3个片段的构造函数中,
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());
答案 1 :(得分:0)
我发现在PHP 7.1中使用parent::$this->appends
导致PHP错误。
这对我有用:
父模型:
<?php
use Illuminate\Database\Eloquent\Model as BaseModel;
class Model extends BaseModel
{
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->append([
'everyChildModelAppendsThis',
]);
}
}
儿童模特:
<?php
class ChildModel extends Model
{
protected $appends = [
'childModelStuff',
];
}