Get junction table in many-to-many AR

I have a many-to-many relationship between users and companies. One user can be assigned to multiple companies and a company can have multiple users. There is a junction table called ‘role’:

user -> role <- company

Pregenerated were:


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getRoles()

    {

        return $this->hasMany(Role::className(), ['user' => 'id']);

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getCompanies()

    {

        return $this->hasMany(Company::className(), ['id' => 'company'])->viaTable('role', ['user' => 'id']);

    }



However the Role table has fields I like to use in my view. For example: isAdmin, isReadOnly.

How can I get these fields all at once, hence loading both Role and Company for a particular User?

Using the getCompanies() or getRoles() yields only one of the tables.

  1. Create a model for your role table.

  2. Use via instead of viatable in getCompanies().

  3. Add additional relation i.e. getRoles().