Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@vcarl
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vcarl/11152248 to your computer and use it in GitHub Desktop.
Save vcarl/11152248 to your computer and use it in GitHub Desktop.
public $findMethods = array('indexed' => true);
/**
* Similar to find('list'), but allows for multiple fields to be retrieved.
*/
protected function _findIndexed($state, $query, $results = array()) {
if ($state === 'before') {
return $query;
}
if ($state == 'after') {
// Temporary array for returning data.
$return = array();
foreach ($results as $key => $result) {
// If there were fields set, use the first one listed as the index. Otherwise, use the id.
if (!empty($query['fields'])) {
$index = $query['fields'][0];
} else {
$index = 'id';
}
$data = $result[$this->alias];
$return[$data[$index]] = $data;
// Unset the key that's now being used as the index, so the data isn't duplicated.
unset($return[$data[$index]][$index]);
// Unset the data that was just copied over from the results.
unset($results[$this->alias][$key]);
}
return $return;
}
}
@vcarl
Copy link
Author

vcarl commented Apr 21, 2014

e.g. if you have the following data in a database:

array(
    (int) 0 => array(
        'User' => array(
            'password' => '*****',
            'id' => '8',
            'username' => 'vcarl',
            'email' => ''
        )
    ),
    (int) 1 => array(
        'User' => array(
            'password' => '*****',
            'id' => '9',
            'username' => 'vcarl1',
            'email' => ''
        )
    ),
    (int) 2 => array(
        'User' => array(
            'password' => '*****',
            'id' => '10',
            'username' => 'vcarl2',
            'email' => ''
        )
    ),
)

and did a find('indexed', array('fields' => array('id', 'username', 'password'), it would return the following data:

array(
    (int) 8 => array(
        'password' => '*****',
        'username' => 'vcarl'
    ),
    (int) 9 => array(
        'password' => '*****',
        'username' => 'vcarl1'
    ),
    (int) 10 => array(
        'password' => '*****',
        'username' => 'vcarl2'
    )
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment