在 Yii2 中从数据库中多态地查找模型 [英] Polymorphically find model from database in Yii2

查看:21
本文介绍了在 Yii2 中从数据库中多态地查找模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库(mysql)中有一张表.但是这个表存储了几种略有不同类型的行.类型取决于此表的 type 列.我有一个表的抽象 ActiveRecord 类和几个后代子类,为不同类型的同一表的行实现略有不同的逻辑.现在我正在为所有类型的行实施更新控制器操作.我获得了行的 id,需要创建一个 ActiveRecord 实例来表示具有此 id 的行.但我不知何故需要根据相应行的类型创建不同子类的实例.

I have one table in the database(mysql). But this table stores several slightly different types of rows. The type depends on this tables's type column. I have an abstract ActiveRecord class for a table and several descendant subclasses implementing slightly different logic for the rows of the same table of different types. Now I am implementing an update controller action for all the types of rows. I am provided with an id of the row and need to create an ActiveRecord instance representing the row with this id. But I somehow need to create instances of different subclasses depending on the type of the corresponding row.

如果我同时获得了类型和 id,我就可以使用工厂来选择相应的子类.但是我已经可以在数据库中拥有该类型并且一个 id 为我提供了足够的信息来从那里选择它.但是,如果我首先从数据库中选择类型,然后创建相应子类的实例,这将意味着执行两次相同的查询.

If I were provided with both a type and an id I could've used a factory to pick a corresponding subclass. But I can already have the type in the database and an id gives me enough information to pick it from there. But if I were to pick the type from the database first and then to create an instance of the corresponding subclass that would've meant executing the same query twice.

我想找到一种从数据库中获取数据的好方法,然后选择一个正确的 ActiveRecord 子类来为其创建一个实例,而不会进行过多的查询或需要过多的数据.Yii2有办法吗?

I want to find a good way to get the data from the database and then pick a right ActiveRecord subclass to create an instance for it without making excessive queries or requiring excessive data. Is there a way to do it Yii2?

或者我应该以不同的方式解决这个问题?实际问题是将几个几乎相同但略有不同的实体存储在一个表中,但业务逻辑略有不同.

Or should I approach this problem somehow differently? The actual problem is having several almost the same but a bit different entities stored in a single table with a bit different business-logic.

推荐答案

解决此问题的方法之一称为单表继承",由 Martin Fowler 这里.samdark(Yii 2 的主要贡献者之一)食谱中也有关于它在 Yii 2 中的实现的好文章,目前正在编写中,但可以在 Github.

One of approaches to this problem is called "Single table inheritance" and described by Martin Fowler here. There is also good article about its implementation in Yii 2 in samdark's (one of the main Yii 2 contributors) cookbook, which is currently in process of writing but is available on Github.

我不会复制整篇文章,但只留下链接也不够.以下是一些重要事项:

I'm not going to copy the whole article, but leaving just link is also not enough. Here are some important things:

1) 为所有类型的对象(例如汽车)创建通用查询:

1) Create common query for all types of objects (for example cars):

namespace appmodels;

use yiidbActiveQuery;

class CarQuery extends ActiveQuery {
    public $type;

    public function prepare($builder)
    {
        if ($this->type !== null) {
            $this->andWhere(['type' => $this->type]);
        }
        return parent::prepare($builder);
    }
}

2) 为每种类型创建单独的模型(从普通模型汽车扩展而来):

2) Create separate model for each type (extending from common model Car):

跑车:

namespace appmodels;

class SportCar extends Car
{
    const TYPE = 'sport';

    public static function find()
    {
        return new CarQuery(get_called_class(), ['type' => self::TYPE]);
    }

    public function beforeSave($insert)
    {
        $this->type = self::TYPE;
        return parent::beforeSave($insert);
    }
}

重型汽车:

namespace appmodels;

class HeavyCar extends Car
{
    const TYPE = 'heavy';

    public static function find()
    {
        return new CarQuery(get_called_class(), ['type' => self::TYPE]);
    }

    public function beforeSave($insert)
    {
        $this->type = self::TYPE;
        return parent::beforeSave($insert);
    }
}

3) 覆盖 Car 模型中的 instantiate() 方法以返回正确类型的汽车:

3) Override instantiate() method in Car model to return correct type of cars:

public static function instantiate($row)
{
    switch ($row['type']) {
        case SportCar::TYPE:
            return new SportCar();
        case HeavyCar::TYPE:
            return new HeavyCar();
        default:
           return new self;
    }
}

然后您可以单独使用任何类型的汽车作为常规模型.

Then you can use any type of cars individually as regular models.

这篇关于在 Yii2 中从数据库中多态地查找模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆