Retrieve data from junction table in Yii2

前端 未结 4 1273
离开以前
离开以前 2021-02-01 09:18

I\'m trying to get data from a join table in Yii2 without an additional query. I have 2 models (User, Group) associated via the junction table (user_group). In

4条回答
  •  渐次进展
    2021-02-01 10:12

    Since I have received no answer for almost 14 days, I'll post how I solved this problem. This is not exactly what I had in mind but it works, that's enough for now. So... this is what I did:

    1. Added a model UserGroup for the junction table
    2. Added a relation to Group

      public function getUserGroups()
      {
          return $this->hasMany(UserGroup::className(), ['user_id' => 'id']);
      }
      
    3. Joined UserGroup in my search model function

      $query = Group::find()->where('id =' . $id)->with('users')->with('userGroups');
      

    This get's me what I wanted, the Group with all Users and, represented by my new model UserGroup, the data from the junction table.

    I thought about extending the query building Yii2 function first - this might be a better way to solve this. But since I don't know Yii2 very well yet, I decided not to do for now.

    Please let me know if you have a better solution.

提交回复
热议问题