Answer the question
In order to leave comments, you need to log in
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')
? <Модель заказчика>
: <Модель подрядчика>;
}
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);
}
Answer the question
In order to leave comments, you need to log in
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.
What you want is generally called polymorphic relations.
Solved differently.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question