问题
是否可以通过与最初进行查询的模型不同的模型返回模型查询结果?
例如,如果我们有两个模型,ModelA
和ModelB
,并且获取一些数据库结果:
$modelA = new ModelA;
$results = $modelA->all();
dd($results);
它可以以某种方式返回ModelA对象,而不是ModelA对象的集合吗?例如,所需的输出:
Collection {#325 ▼
#modelA_Table: Array:4 [▼
0 => ModelB { #297 ▶}
1 => ModelB { #306 ▶}
2 => ModelB { #311 ▶}
3 => ModelB { #318 ▶}
]
}
上下文
关系是一个分类层次结构,其中ModelB
是ModelA
的子分类。
class ModelA extends Model {
protected $table = 'ModelA_Table';
protected $fillable = [];
private $discriminator = 'a_type';
public function __construct(array $attributes = array()){
$this->initialize();
parent::__construct($attributes);
}
private function initialize() {
$this->fillable = array_merge($this->fillable, $this->fillables());
}
private function fillables() {
return [
'a_name',
'a_type'
'a_price'
];
}
}
class ModelB extends ModelA {
protected $fillable = [];
public function __construct(array $attributes = array()){
$this->initialize();
parent::__construct($attributes);
}
private function initialize() {
$this->fillable = array_merge($this->fillable, $this->fillables());
}
private function fillables() {
return [
'b_width',
'b_height'
];
}
}
这两个模型都是通过单表继承(ModelA_Table)持久化的单个实体的不同分类单元(分类级别)。
类推-总则:具体::ModelA : ModelB ::Vehicle :卡车
回到代码中,当ModelB被实例化时,它将通过构造函数中的初始化()将自己的填充附加到其继承的父-填充项中。如果ModelB可以继承ModelA的可填充性,则相反是不正确的;ModelA不能继承ModelB的可填充项。我可以要求卡车->find(1)并同时获得卡车和车辆属性,但是Vehicle->find(1)只会给我车辆属性,因为Vehicle (一般分类法)不能从它的子类继承(从特定的分类法)。
这就让我呆在现在的地方。
基本上,如果ModelA是Vehicle,而ModelB是Car,我需要这样做:
1)车辆模型按id取行
2)车辆模型着眼于场“a_type”
( 3)“a_type”将是“汽车”、“摩托车”或“卡车”等。
4)返回的水合对象将属于“a_type”类
使用ModelA查询,使用ModelB获取结果。
发布于 2016-02-29 09:25:00
我用杰夫·马德森的解决方案修改了雄辩模型的newFromBuilder
方法解决了这个问题。
Model.php:
public function newFromBuilder($attributes = array())
{
$instance = $this->newInstance(array(), true);
$instance->setRawAttributes((array) $attributes, true);
return $instance;
}
在扩展类时覆盖:
public function newFromBuilder($attributes = array())
{
$class = $this->{$this->discriminator} . ucwords($attributes->status);
$instance = new $class;
$instance->exists = true;
$instance->setRawAttributes((array) $attributes, true);
return $instance;
}
新的类是$class
,它是检索到的判别器字段的值,该字段由属性discriminator
指定。
https://stackoverflow.com/questions/35692978
复制相似问题