Tuesday, March 30, 2010

Re: find() using multiple references to the same table

OK so you have the following

Application belongsTo School
Application belongsTo Student
Student belongsTo School

In order to run a find on Application but place a condition on the
Student's current school you need to force a join using bindModel() as
follows

$this->Application->bindModel(array(
'belongsTo' => array(
'CurrentSchool' => array(
'className' => 'School',
'foreignKey' => false,
'conditions' => array('Student.school_id = CurrentSchool.id')
)
));

If you are going to paginate your result you need to add a false
parameter to make this permanent (but only for this HTTP request)

$this->Application->bindModel(array(
'belongsTo' => array(
'CurrentSchool' => array(
'className' => 'School',
'foreignKey' => false,
'conditions' => array('Student.school_id = CurrentSchool.id')
)
), false);

For more info on ad-hoc joins see:
http://book.cakephp.org/view/86/Creating-and-Destroying-Associations-on-the-Fly

Now you can run the following find

$this->Application->find('all', array(
'conditions'=>array(
'Application.school_id'=>$school_id,
'CurrentSchool.name'=>$school_name
)
));

However, if you are using and id for searching the applied to school,
why are you not able to use an id for the current school (by providing
a select list)? Then you could just apply the condition to
Student.school_id and not have to force any joins.

HTH

Paul.

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

To unsubscribe from this group, send email to cake-php+unsubscribegooglegroups.com or reply to this email with the words "REMOVE ME" as the subject.

No comments: