1

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 ...

tshepang
  • 12,111
  • 21
  • 91
  • 136
SkyStar
  • 169
  • 1
  • 3
  • 14
  • Diagram of database tables: http://i.stack.imgur.com/jAhCq.gif – SkyStar Aug 21 '13 at 11:34
  • 1
    forget books, read the docs [**Yii Doc**](http://www.yiiframework.com/doc/guide/1.1/en/database.arr) it is explained really well. – itachi Aug 21 '13 at 11:42

1 Answers1

0

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

Telvin Nguyen
  • 3,569
  • 4
  • 25
  • 39