Skip to content

Instantly share code, notes, and snippets.

@davidyell
Last active February 25, 2016 10:06
Show Gist options
  • Save davidyell/6061728 to your computer and use it in GitHub Desktop.
Save davidyell/6061728 to your computer and use it in GitHub Desktop.
Find's in CakePHP
<?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