Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Get list of records, with database ID as key

I want a quick and easy way to get a list of values from a table as an associative array, in wich the keys would be the ID of the table, and the value, any field of the database.

I mean, i want to do this with a one-liner:

    $projects = [];
    foreach (Projects::find(['columns' => ['id', 'name']])->toArray() as $key => $project) 
    {
        $projects[$project['id']] = $project['name'];
    }

But I can't find a practical way to do it, I also know CakePHP, and with cake you would do something like this:

    $this->Projects->find('list');

(Having previously defined the key and value fields in the model)

Any suggestions? If it's not implemented, I think it would be a really cool feature to have :D



68.4k
Accepted
answer

It's not implemented. I always have custom method in the model I need, because I have to join 1-2 tables before I get the desired output.

Here is a very simple method you can put in your BaseModel and use it everywhere:

public static function toList($where = '', $columns) 
{
    $items = self::find([
        'conditions' => $where,
        'columns' => $columns
    ]);

    $collection = [];
    foreach ($items as $item) {
        $collection[$item->{$columns[0]}] = $item->{$columns[1]};
    }
    return $collection;
}

How to use:

$items = \Models\Countries::toList('id > 100', ['id', 'code']);
edited May '17

One-liner:

$projects = array_walk(Projects::find(['columns' => ['id', 'name']]), function(&$v, &$k) { $k = $v['id']; $v = $v['name']; });

Everything can be a one liner if you are brave enough :D

Awesome guys! Handy snippets, Thanks!