smart way to retrieve records limited by visibility ?

I have 3 tables

  • user - say user A

  • project - say I have project A, B and C

  • user_has_project - say user A allow to work with Project A and C

The idea is if user A is allowed to work with Project A and C only, every where in the web application user A can only see Project A and C, not B.

To query Project, I usually do


$project = Project::find()->where( etc ... )

To take project visibility of user into consideration, I would do


Project::find()

->innerJoin('user_has_project', 'user_has_project.project_id = project.id')

->where(['user_has_project.user_id' => Yii::$app->user->id]);



Is there a better way to do the above ? Lots of code duplication if I just copy and paste




->innerJoin('user_has_project', 'user_has_project.project_id = project.id')

->where(['user_has_project.user_id' => Yii::$app->user->id])

everytime I need to work on Project object.

You can customize query class so it will be added every time automatically.

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#customizing-query-classes