Skip to content

Instantly share code, notes, and snippets.

@gothedistance
Last active December 19, 2015 09:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gothedistance/5931772 to your computer and use it in GitHub Desktop.
Save gothedistance/5931772 to your computer and use it in GitHub Desktop.
CakePHPで深いJoinが必要な場合は、Containableを使うよりも確実に以下のTipsに従ったほうがいい。確実でしかもSQLもシンプルになり、早い。 Via http://mark-story.com/posts/view/using-bindmodel-to-get-to-deep-relations
CakePHP Behaviouer 'Containable' is very useful,but it's not suitable plugin for fetch deep join records.
I want to join 4 Tables as such.
OrderEntryDetail->Item->Maker->Category
Containable runs sql for each model(equivalent each table) but this tricky BindModel/UnBindModel usage solves this problem.
<Before>
<?php
$OrderEntryDetail->find('first', array(
'conditions' => array('Item.id' => $itemId),
'contain' => array('Item' => array('Maker' => array('Category')))
));
?>
<After>
<?php
$OrderEntryDetail->unbindModel(array(
'belongsTo' => array('Item')
));
$OrderEntryDetail->bindModel(array(
'hasOne' => array(
'Item' => array(
'foreignKey' => false,
'conditions' => array('OrderEntryDetail.item_id = Item.id')
),
'Maker' => array(
'foreignKey' => false,
'conditions' => array('Item.maker_id = Maker.id')
),
'Category' => array(
'foreignKey' => false,
'conditions' => array('Item.category_id = Category.id')
),
)
));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment