Home » Php » php – Yii2 viaTable join condition

php – Yii2 viaTable join condition

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is it possible to set condition in join section in viaTable?
Currently I got this:

return $this->hasMany(User::className(), ['id' => 'id_user'])
                    ->from(User::tableName())
                    ->viaTable(RoomActiveUser::tableName(), ['id_room' => 'id'],
                        function($query) {
                        return $query->andWhere(['id_role' => 
                                 RoleHelper::getConsultantRole()->id]);
                    });

But it’s not a good solution. Why?
When you do a left join the id_role condition will make it inner join actually. The id_role condition should be placed inside ON section of the join.

I was searching the web plus inspecting the code but I don’t see how it could be solved.

How to&Answers:

I got the answer from Qiang Xue – $query->onCondition() should be used for what I need. Result code:

return $this->hasMany(User::className(), ['id' => 'id_user'])
                    ->from(User::tableName())
                    ->viaTable(RoomActiveUser::tableName(), ['id_room' => 'id'], 
                        function($query) {
                          $query->onCondition(['id_role' => 
                             RoleHelper::getConsultantRole()->id]);
                      });

Answer:

Have you tried doing it like

->viaTable(RoomActiveUser::tableName(), ['id_room' => 'id', 'id_role' => RoleHelper::getConsultantRole()->id])

This should create a JOIN X on 'id_room' = 'id' AND 'id_role' = '$ConsultantRole_id'