Yii2 viaTable join condition

11,822

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]);
                      });
Share:
11,822
Joe
Author by

Joe

Web, desktop and DB developer. Passionate about databases. Very happy to do anything in C#. Enthusiast of logic, objectivity, patterns and abstraction!

Updated on June 04, 2022

Comments

  • Joe
    Joe almost 2 years

    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.