[英]Laravel 5 - query using a model, get results with a different model
是否可以通过不同于最初查询的模型返回模型查询结果?
例如,如果我们有两个模型ModelA
和ModelB
,并且获取一些数据库结果:
$modelA = new ModelA;
$results = $modelA->all();
dd($results);
它可以以某种方式返回ModelB对象,而不是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 ::车辆:卡车
回到代码中,当实例化ModelB时,它将通过构造函数中的initialize()将其自己的fillable附加到其继承的parent-fillable中。 如果ModelB可以继承ModelA的可填充内容,则情况并非如此。 ModelA无法继承ModelB的可填充对象。 我可以要求提供Truck-> find(1)并同时获得Truck和Vehicle属性,但是Vehicle-> find(1)只会为我提供Vehicle属性,因为Vehicle(常规分类法)不能从其子项(特定分类法)继承)。
那让我留在了我现在的位置。
基本上,如果ModelA是Vehicle,ModelB是Car,则我需要这样做:
1)车辆型号按ID提取
2)车辆模型查看字段“ a_type”
3)'a_type'将是'Car','Motorcycle'或'Truck'等
4)返回的水合对象将属于'a_type'类
我使用Jeff Madsen的修改newFromBuilder
模型的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字段的值,该字段由属性discriminator
指定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.