Answer the question
In order to leave comments, you need to log in
How to form an unusual query on Yii2 related tables?
There are 2 tables with a many-to-many relationship.
First (users)
id | name
1 | maxim
2 | lena
Second (roles)
id | role_name
1 | admin2
| moder
3 | author
AND relation table
id | user_id | role_id
1 | 1 | 2
2 | 2 | 2
3 | 2 | 3
And so Maxim we have only moderator and Lena and moder and author.
The Users model has a relationship
public function getRoles(){
return $this->hasMany(Roles::className(),['id'=>'role_id'])
->viaTable('relation', ['user_id' => 'id']);
}
$query = Users::find()
->joinWith(['roles rl'])
->andWhere(['rl.id', $searchModel->roles])
->all();
$query = Users::find()
->joinWith(['roles rl']);
foreach ($searchModel->roles as $role){
$query->andWhere(['=','rl.id', $role]);
}
$result = $query->all();
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question