Filtering model by default with joined table

Hi, All!

I’m creating a project manager system. So, I have list of projects and tasks which assigned to project. And a have one more table with access information between users and projects:


Projects

id | name

1    Project 1

2    Project 2


Tasks

id | project_id | name

1          1      Task 1 

2          2      Task 2


Users

id | name

1    User 1 

2    User 2


Project Access

id | user_id | project_id

1      2           1

2      2           2 

3      1           1

So, what I trying to do is show project and tasks list according to authorized user id.

For this issue I have override find() method in my model:


public static function find()

{

    $query = new ProjectsQuery(get_called_class());


    $query->joinWith([

        'projectsAccessibility' => function($query){

            $query->onCondition(['user_id' => Yii::$app->user->id]);

        },

    ]);


    return $query;

}

And it’s working good until I trying create a new task item I got an error:


SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous

The SQL being executed was: SELECT EXISTS(SELECT tm_projects.* FROM tm_projects LEFT JOIN tm_projects_accessibility ON (tm_projects.id = tm_projects_accessibility.project_id) AND (user_id=37) WHERE id='1')

If I’m right, this error shows when yii2 trying to check all attributes in validateAttributes() method during save(). And because it doesn’t know about joined table in find() method with same column name - id I have this problem. And I don’t know how to do now :(

I will happy and thankful for any suggestion about my issue!

I think "find()" should not contain a code joining a related table. Consider creating a custom method for joining the table in your custom query class.

Customizing Query Classes

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