phpcakephpcakephp-2.0cakephp-model

Performing a simple find operation in CakePHP


Using CakePHP, I need to retrieve a basic list of records. No joins or special CakePHP result formatting, just a basic array of records in the following data format:

[
    {first_name: 'Matthew', last_name: 'Stafford', gender: 'male'},
    {first_name: 'Jason', last_name: 'Hanson', gender: 'male'}
]

What's the simplest way to do this using Cake Models?


Solution

  • With proper MVC separation, outputting a JSON formatted result like that would look something like this:

    Controller:

    $people = $this->Person->find('all', array('conditions' => ...));
    $this->set(compact('people'));
    

    View:

    echo json_encode(array_map(function ($p) { return $p['Person']; }, $people));