http://mark-story.com/posts/view/using-bindmodel-to-get-to-deep-relations
Now we want to find the Division that a particular Item belongs to. In normal SQL we could do
SELECT Division.id FROM items AS Item LEFT JOIN categories AS Category ON Category.id = Item.category_id LEFT JOIN sections AS SECTION ON SECTION.id = Category.section_id LEFT JOIN divisions AS Division ON Division.id = SECTION.divison_id WHERE Item.id = $id
And everything will happen in one query. In CakePHP we could use Containable to get at these deep relations. With a find call like
$this->find('first', array( 'conditions' => array('Item.id' => $itemId), 'contain' => array('Category' => array('Section' => array('Division'))) ));
This will work just fine however, it will also do 3 queries, one per table. In order to get the optimal query and stay inside the realm of non query()
function we can use some bindModel()
trickery.
$this->unbindModel(array( 'belongsTo' => array('Category') )); $this->bindModel(array( 'hasOne' => array( 'Category' => array( 'foreignKey' => false, 'conditions' => array('Category.id = Item.category_id') ), 'Section' => array( 'foreignKey' => false, 'conditions' => array('Section.id = Category.section_id') ) 'Division' => array( 'foreignKey' => false, 'conditions' => array('Division.id = Section.division_id') ) ) )); $result = $this->find('first', array( 'conditions' => array('Item.id' => $id), 'contain' => array('Category', 'Section', 'Division'), 'fields' => array('Division.id') ));
The above although much longer will create only one query. This will provide the fastest result performance wise.
منتشر شده در:Cakephp
تگ شده در:bindmodel