David
David

Reputation: 4518

yii2 getting data from two models and presenting it in view

I have two models users and pictures To draw all pictures in view I have to get string from pictures, one of data is userID, then get string from users according to that userID, so I get userFolder Then I can draw picture using combined data.

And this must be done for all pictures in DB.

I can start from controller

$picturesModel= Pictures::find()->all();

But then I have to do what? run a loop while which get users data, and then get complete data for drawing a picture and store it in some new array which after loop finish I should pass to view? Is this the best way ? or there is anything simple ?

Upvotes: 1

Views: 87

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133400

Assuming that your Pictures has a relation one to one with Users the you can add to you Pictures model a function

class Pictures extends ActiveRecord
{
    // ...

    public function getUser()
    {
        return $this->hasOne(Users::className(), ['id' => 'user_id']);
    }
}

then if you controller or in your view you need accessing to the user related to the picture you can

$pictureModel = Pictures::find()->where(['id'=>123])->one();

You can access to the user related

$userModel= $pictureModel->User;

or for a collection of pictures

$picturesModels= Pictures::find()->all();

$userModel = $picturesModels[0]->user

or for the loop

$picturesModels= Pictures::find()->all();

foreach( $picturesModels as $key => $value ) {

  echo $value->user->your_att;  
}

you can take a look at http://www.yiiframework.com/doc-2.0/guide-db-active-record.html and http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#relational-data

Upvotes: 1

Related Questions