Find by relation ?

Hi all ,

I have three Models :

  • User : id,username,email…etc

  • Category : id,name

  • UserCategory : user_id, category_id

User Model has these relations :




  public function getUserCategories()

    {

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

    }




    public function getCategories()

    {

        return $this->hasMany(Category::className(), ['id' => 'category_id'])

            ->via('userCategories');

    }



Each user has many categories ,

How can I query users of specific category ? I want to find all users in category.id = 3 ?

Thank you

Should be:




$usersInCategory = User::find()->with('categories')->where(['categories.id' => 3])->all();



Didn’t work :

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘categories.id’ in ‘where clause’

The SQL being executed was: SELECT * FROM user WHERE categories.id=3

Solved :




$usersInCategory = \common\models\User::find()->joinWith('categories')->where(['category.id' => 10])->all();



Thank you