L
L
lolka022018-10-05 13:43:58
Yii
lolka02, 2018-10-05 13:43:58

How to call a model on a due date?

Known id and model name in string form. let's say:

use common\models\Article
.....
$id = 2;
$model = 'Article';
$model::findOne($id); //как то так вызвать.

I plan to write down the id and the name of the models in one table, then make a selection if necessary from this data. Is it possible to make a universal code without any conditions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-10-05
@lolka02

You need to get the class by name, and then refer to its static property. Something like this:

$id = 2;
$c_name = 'common\models\Article';
$obj = new $c_name();
$obj::findOne($id);

or
$c_name = 'common\models\Article';
$obj = Yii::createObject($c_name);
$obj::findOne($id);

or
$obj = Yii::createObject([
            'class' => 'common\models\Article',
            'some_attr' => 'алюминий',
             ]);
$obj::findOne($id);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question