Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 viaTable join condition

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.

like image 434
Joe Avatar asked Dec 01 '14 14:12

Joe


1 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]);
                      });
like image 142
Joe Avatar answered Sep 21 '22 18:09

Joe