Sending relationship data from controller to view

Bit of a Yii2 noob here and probably a straight forward problem.

How can I send data from another model (Team) to the User model?

I’ve setup the relationship between the models in the User model:




public function getTeams()

    {

        return $this->hasMany(Team::className(), ['user_id' => 'id']);

    }




In the User controller, I’ve got this standard actionView code:




public function actionView($id)

    {

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

            'model' => $this->findModel($id),

        ]);

    }



I’ve tried doing things like changing it to:




public function actionView($id)

    {

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

            'model' => $this->findModel($id),

            'teams' => $this->getTeams(),

        ]);

    }



but i get a ‘Calling unknown method’ error.

I think I’m on the right track, I just don’t know how to write the actionView correctly for a 2nd model.

Hi

send the model like this:

in this code you already send teams data with model object.




public function actionView($id)

    {

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

            'model' => $this->findModel($id),

        ]);

    }

and in view you can iterate over $model->teams

Spot on, thanks Abed. I’m loving the simplicity of Yii2.

I’ve also found that if you want to setup a dataprovider for a related model, you can structure the actionView like:




public function actionView($id)

    {

        $model = $this->findModel($id);

        $dataProviderTeams = new ActiveDataProvider([

            'query' => $model->getTeams(),

        ]);


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

            'model' => $model,

            'dataProviderTeams' => $dataProviderTeams,

        ]);

    }