Question

I read a book Pactpub Web Application Development with Yii and PHP Nov 2012. Faced with such a problem, I can not understand the logic behind the use of relations (). Here diagram tables in the database:

You need to insert code in the model:

Issue model:

...
'requester' => array(self::BELONGS_TO, 'User', 'requester_id'),
'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),
'project' => array(self::BELONGS_TO, 'Project', 'project_id'),
);
...

Project model:

...
'issues' => array(self::HAS_MANY, 'Issue', 'project_id'),
'users' => array(self::MANY_MANY, 'User', 'tbl_project_user_assignment(project_id, user_id)'),
...

I can not understand that we add? If the model Issue understand everything, then the model Project - I do not understand that we are adding. Help to understand ...

Was it helpful?

Solution

If the model Issue understand everything, then the model Project - I do not understand that we are adding

in some case, you have already had a project, and you would like to find all of issues and partner users of that project.

$project = Project::model()->findByPK(1); // get project id=1

$issues = $project->issues; // get all of issues of project id=1, the result would be array
$users = $project->issues; // get all of users of project id=1, the result would be array

$project = Project::model()->with('issues', 'users')->findAll(); // get all of projects which has issue and user

//you have a user name ABC, and you want to find all of projects which contains a issue from owner has that user name.

$projects = Project::model()->with(array(
            'issues' => array(
                'alias' => 'issue',
                //'condition' => '',
                //'params' => array(),
                'with' => array(
                    'owner'=>array(
                        'alias' => 'user',
                        'condition' => 'username =:username',
                        'params' => array(':username'=>'ABC'),
                    )

                )
            ),

        ))->findAll();

There has many ways let you mix them up with multiple relations and conditions. One of above example would generate some big SQL SELECT query that I never want to deal with on my own :)

AR Relations Details

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top