Last active
February 25, 2016 10:06
-
-
Save davidyell/6061728 to your computer and use it in GitHub Desktop.
Find's in CakePHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
These are some example files for CakePHP 2.x | |
Using containable | |
The problem with this is that if Group doens't match, then it will just return a blank array | |
dimension, because containable is just going to join the arrays in php | |
*/ | |
$this->User->find('first', array( | |
'contain' => array( | |
'Group' => array( | |
'conditions' => array( | |
'Group.id' => $groupId | |
) | |
) | |
), | |
'conditions' => array( | |
'User.id' => $userId | |
) | |
); | |
/* | |
Using Linkable (https://github.com/lorenzo/linkable) | |
This will do the same as above, but force a join. So if group doesn't match, you won't even get a result | |
*/ | |
$this->User->find('first', array( | |
'link' => array( | |
'Group' | |
), | |
'conditions' => array( | |
'User.id' => $userId, | |
'Group.id' => $groupId | |
) | |
); | |
/* | |
Using joins | |
This does the same as above, but obviously is a bigger find | |
*/ | |
$this->User->find('first', array( | |
'joins' => array( | |
array( | |
'table' => 'groups', | |
'alias' => 'Group', | |
'type' => 'LEFT', | |
'conditions' => array( | |
'Group.id' => $groupId | |
) | |
) | |
), | |
'conditions' => array( | |
'User.id' => $userId | |
) | |
); | |
/* | |
* Using Paginate with Containable | |
*/ | |
// Load the component | |
$components = array('Paginator'); | |
// Paginate contained data | |
$this->Paginator->settings = array( | |
'contain' => array( | |
'Group' => array( | |
'conditions' => array( | |
'Group.id' => $groupId | |
) | |
) | |
), | |
'conditions' => array( | |
'User.id' => $userId | |
) | |
'limit' => 10 | |
); | |
$this->Paginator->paginate($this->User); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment