H
H
HaruAtari2014-04-09 12:37:49
Yii
HaruAtari, 2014-04-09 12:37:49

Yii: how to change model class from ancestor to successor on the fly?

Good afternoon.
There is an entity "user" and two child entities "contractor" and "customer". The User model contains methods common to both descendants and a getType() method that determines who the current user is.
I need the find method to return an object of the Employee or Customer class, depending on its type. Something like:

public function find($condition='', array $params=[]) {
$user = parent::find($condition, $params);
  return ($user->getType() == 'customer')
    ? <Модель заказчика>
    : <Модель подрядчика>;
}

But how to make an instance of the inheritor class from the current class? Simply assigning attributes will not work. many private properties.
The only way out that I see is to make a request to select an object for one of the heirs inside the method. Like the following:
public function find($condition='', array $params=[]) {
$user = parent::find($condition, $params);
  return ($user->getType() == 'customer')
    ? Customer::model()->findByPk($user->id)
    : Employee::model()->findByPk($user->id);
}

But this solution seems to me somewhat crutch.
Could you tell me how to organize such a method?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
MaxHero, 2014-04-13
@HaruAtari

Your task is solved using the CActiveRecord::instantiate method . In this method, we parse the values ​​of the row fields from the database (type field) and return a new instance of the required object.

Y
Yuri Morozov, 2014-04-09
@metamorph

What you want is generally called polymorphic relations.
Solved differently.

M
Maxim Kolokolnikov, 2014-04-11
@maxmirazh33

You need a later static link...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question