There is a user table and a table of records. One entry may have multiple users. All this is stored in a related table:

user_id | item_id | rights

You need to select all users for the record and also select the rights for each user of the record from the related table, like this

public function getUsers() { return $this->hasMany( User::className(), ['id' => 'user_id']) ->viaTable('{{%user_items}}', ['item_id' => 'id']) ->leftJoin('{{%user_items}}', ['item_id' => $this->id]) ->select('*'); } 

It works, the only thing that confuses is $this->id . If I write ' id ' instead of $this->id I get NULL

  • Added another user with the same item_id, now doesn’t choose :( - Guest

1 answer 1

Try to describe join like this:

 ->leftJoin('{{%user_items}}', 'item_id = id') 

those. not an array but a string

  • Thanks, already figured it out. True left $ this-> id, because after leftJoin, you get the id user, not the id item, i.e. the id after the leftJoin is set to the user id value, not the record id. - Guest