0

I had a DB that had a user table and a group table and the group table had a column user_id which made it simply to return a list of users in a group:

$users = User::find()
  ->where(['{{user}}.group_id' => $group_id])
  ->all();

Now the user_id column is gone and there is a third table group_user with user_id and group_id columns for the relationship.

I tried this:

$users = User::find()
  ->innerJoinWith('group_user)
  ->where(['{{group_user}}.group_id' => $group_id])

but received this error:

User has no relation named "group_user"

But I set the relationship in the User model:

public function getGroupUser() {
    return $this->hasOne(GroupUser::className(), ['user_id' => 'id']);
}

What am I missing? This is used in a Humhub API.

lilbiscuit
  • 2,109
  • 6
  • 32
  • 53

1 Answers1

3

I would reprogram your getGroupUser (renaming it to getGroups) relation using viaTable:

public function getGroups() {
    return $this->hasMany(Group::className(), ['user_group.id_group' => 'group.id'])
        ->viaTable('user_group', ['user.id' => 'user_group.id_user']);
}

That would give you the Group(s) a User belongs to. But I think you are aiming to get the Users that belong to a given group, so similarly I would create a getUsers relation in your Group model:

public function getUsers() { 
      return $this->hasMany(User::className(), ['id' => 'user_id']) 
        ->viaTable('group_user', ['group_id' => 'id']); 

}

Then:

$group = Group::findOne($id_group);
$users = $group->getUsers()->all();
gmc
  • 3,910
  • 2
  • 31
  • 44
  • `Getting unknown property: \\api\\models\\Group::group_user.group_id` on this function: `public function getUsers() { return $this->hasMany(User::className(), ['group_user.user_id' => 'user.id']) ->viaTable('group_user', ['group.id' => 'group_user.group_id']); }` – lilbiscuit Apr 05 '17 at 15:41
  • I had a typo, `=` instead of `=>`. I also updated tables and column names – gmc Apr 05 '17 at 15:45
  • No problem ... I caught the typos, including table and field names ;) – lilbiscuit Apr 05 '17 at 15:46
  • OK I got rid of that error by changing getUsers() to: `public function getUsers() { return $this->hasMany(User::className(), ['group_user.user_id' => 'user.id']) ->viaTable('group_user', ['group_user.group_id' => 'id']); }` But now I get an error `Undefined index: user.id` on that function. – lilbiscuit Apr 05 '17 at 16:01
  • What is the primary key of your user table? it is not `user.id`? – gmc Apr 05 '17 at 16:03
  • Yes it is `user.id` – lilbiscuit Apr 05 '17 at 16:04
  • What if your replace `user.id` with `id`? – gmc Apr 05 '17 at 16:07
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/139995/discussion-between-gmc-and-lilbiscuit). – gmc Apr 05 '17 at 16:08