I'm trying to get a many-to-may relationship to work, but I can't get it to work.
I have a database with 3 tables: users
, favorites
& videos
. The favorites table contains 2 foreign keys
that point to the users table and the videos table.
Currently I have the following:
User Model:
public function getVideos()
{
return $this->hasMany(Video::class, ['id' => 'video_id'])->viaTable(UserFavorites::tableName(), ['favorite_id' => 'id']);
}
Video Model:
public function getUsers()
{
return $this->hasMany(User::class, ['id' => 'user_id'])->via(UserFavorites::tableName());
}
VideoController: (ActiveController)
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
$user = User::findOne('1=1');
return new ActiveDataProvider([
'query' => $user->getVideos()
]);
}
Following what they did in:
Many-to-many relation in yii2 activedataprovider
but that did not work. I also tried with extraFields
and expand
with no luck.
How do I make it so the result will look sorta like this:
[{
"id": 1,
"name": "video name",
"likes": 69,
"user": [{
"id": 1,
"name": "John"
}]
},
...
]