T
T
twopizza2016-05-06 18:28:24
Yii
twopizza, 2016-05-06 18:28:24

How to create objects of different classes depending on an attribute in Yii2?

There is a basic model, there are its heirs. It is necessary that, depending on the attribute, for example type, a new model of the {Type}{BaseModel} class is created, if type is specified, or of the {BaseModel} class, if type is not specified. How can this be implemented?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Donkovtsev, 2016-05-06
@Demetriy

single table inheritance

V
Viktor, 2018-02-26
@shviktor

To do this, you need to override the ActiveRecord instantiate static method, which is responsible for creating the model object

static function instantiate($row)
    {
        if ($row['type'] == self::TYPE_ARTICE)
            return new Article();

        return new static();
    }

The logic of the method is taken from the head, well, the essence must be understood

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question