Call to a member function createCommand() on a non-object

Hi all!

I’m probably not doing this right anyway, but thought I would share a problem.

I have a table called persons

This has a 1=1 table called student

If someone creates a person, that is of the type = Student, then I want to create the student record.

I tried to use the following code, but get an error.

Here is the code:




    public function actionCreate()

    {

        $model = new Persons();


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

           

            //if the person is created as student, init the student record

        if($model->type == 'Student') {

            $db->createCommand()->insert('student', [

                'id' => $model->id,

            ])->execute();

        }

            

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }



Here is the error:


 PHP Fatal Error – yii\base\ErrorException

Call to a member function createCommand() on a non-object

It seems to be highlighting this line of code:


$db->createCommand()->insert('student', [

Help is greatly received, thank you!

For those who might need help with this:

The problem was a basic PHP problem where I had copied code but had not initialised my variable.

As the DB connection was already initialised, I just needed to use:


Yii::$app->db

So the full fixed function is now:


    public function actionCreate()

    {

        $model = new Persons();


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

           

            //if the person is created as student, init the student record

        if($model->type == 'Student') {

            Yii::$app->db->createCommand()->insert('student', [

                'id' => $model->id,

            ])->execute();

        }

            

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }