首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Laravel 5-使用模型进行查询,获得不同模型的结果。

Laravel 5-使用模型进行查询,获得不同模型的结果。
EN

Stack Overflow用户
提问于 2016-02-29 06:09:41
回答 1查看 728关注 0票数 0

问题

是否可以通过与最初进行查询的模型不同的模型返回模型查询结果?

例如,如果我们有两个模型,ModelAModelB,并且获取一些数据库结果:

代码语言:javascript
代码运行次数:0
运行
复制
$modelA = new ModelA;

$results = $modelA->all();

dd($results);

它可以以某种方式返回ModelA对象,而不是ModelA对象的集合吗?例如,所需的输出:

代码语言:javascript
代码运行次数:0
运行
复制
Collection {#325 ▼
    #modelA_Table: Array:4 [▼
        0 => ModelB { #297 ▶}
        1 => ModelB { #306 ▶}
        2 => ModelB { #311 ▶}
        3 => ModelB { #318 ▶}
    ]
}

上下文

关系是一个分类层次结构,其中ModelBModelA的子分类。

代码语言:javascript
代码运行次数:0
运行
复制
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获取结果。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-29 17:25:00

我用杰夫·马德森的解决方案修改了雄辩模型的newFromBuilder方法解决了这个问题。

Model.php:

代码语言:javascript
代码运行次数:0
运行
复制
public function newFromBuilder($attributes = array())
{
    $instance = $this->newInstance(array(), true);

    $instance->setRawAttributes((array) $attributes, true);

    return $instance;
}   

在扩展类时覆盖:

代码语言:javascript
代码运行次数:0
运行
复制
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指定。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35692978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档