Getting data from yii2 hasmany() function

4.3k views Asked by At

I am working with yii2 to make a basic website.

I need to load a users liked videos when they have logged on.

In the database the Videos are stored in the video table, Users are stored in the user table, UserVideoJunction is the junction table that stores the relationship between the users and videos.

When I use Gii to generate the models and CRUD for the 3 tables all is fine I can access and manipulate all the data.

But the problem arises when I try get the Videos that are related to a User.

public function getUservideojunctions()
{
    return $this->hasMany(Uservideojunction::className(), ['UserID' => 'UserID']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getVideos()
{
    return $this->hasMany(Video::className(), ['P_ID' => 'VideoID'])->viaTable('UserVideoJunction', ['UserID' => 'UserID']);
}

The code above is the automatically generated code.

Could some please tell me how to display what is returned by the getVideos() function?

2

There are 2 answers

0
lndim On

Try this:

$videos = $user->videos;

Or this:

$videos = $user->getVideos()->all();
0
Stanimir Stoyanov On

Usage of hasMany is well explained in the User Guide.

Calling getVideos() returns only the ActiveQuery instance. You need to use it somehow to get your results.

You can get all rows in your many-to-many relation:

$videos = $user->getVideos()->all();

Also, you can filter them like this:

$videos = $user->getVideos()
     ->where(['>', 'year', 2000])
     ->orderBy('id')
     ->all();

Basically, after getVideos() you can filter, group, count, sort, do anything with the ActiveQuery, just like you do when using find().