Rahman
Rahman

Reputation: 452

How to create a model object in yii2 by string name?

I need to create a model by string name that it is a variable.

       function($modelName){ 
               $modelName= "backend\\models\\".$modelName;

               $modelClass = Yii::createObject([
                          'class' => $modelName,
                    ]); 
                    $model =  $modelClass::find(); 
            }

when I pass Book(it is extracted form DB) as modelName to function, it throws an error: Class backend\models\Book does not exist. but when I write $modelName= "backend\\models\\Book"; it works fine.

I know it is because of run time and compile time. but I don't know how to solve it. because $modelName is Characterized at run time.

Upvotes: 1

Views: 1135

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133380

You are accessing to a static method using an object. You should access to the static method just using the class name eg:

$modelName = 'backend\models\\' . $modelName;
$model = $modelName::find(); 

And remember that $modelName::find() don't return a model but just the query object for a model. To obtain a model you should use eg: $modelName::find()->where(['id'=>$your_value])->one();

Upvotes: 2

Related Questions