yii - Double Join Select -
three tables project, users, issues.
- project table columns: p_id,name,...
- users table columns: u_id username...
- issues table columns: i_id i_name...
relations:
- project has many users - 1..*
- project has many users - 1..*
- project has many issues - 1..*
- users has many issues - 1..*
what want do:
in yii framework logic: select project it's users, these users has have issues of selected project.
in tables logic: select issues of project and user.
what sql code want mimic:
select issue.i_name issue join project on issue.i_id = project.p_id join user on issue.i_id user.u_id
what want in yii:
//get project $model = project::model()->findbypk( $p_id ); //get project's users $users = $model->users; //get each of users issues of selected project foreach( $users $user ) $issues = $user->issues;
to solve have use through in ralations method.
project model relations method should this:
public function relations() { return array( 'users' => array(self::many_many, 'user', 'tbl_project_user_assignment(project_id, user_id)'), //'issues' => array(self::has_many, 'issue', 'project_id'), 'issues' => array(self::has_many,'issue',array('id'=>'owner_id'),'through'=>'users'), 'columns' => array(self::many_many, 'column', 'tbl_project_rel_column(p_id,c_id)'), ); }
now in action select project, it's users , users's posts(or in case issues) of selected project:
$project = project::model()->with('users','issues')->findbypk(1); $users = $project->users; foreach($users $user) { echo $user->username."<br/>"; } $issues = $project->issues; foreach($issues $issue) { echo $issue->name."<br/>"; }