Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent get() indexed by primary key id

I often find it very useful to index my results by the primary key id.

Example:

$out = [];

$users = User::where('created_at', '>=', '2015-01-01')->get();

foreach ($users as $user) {
    $out[$user->id] = $user;
}

return $out;

Is there anyway to do this in one shot with Eloquent? It's not useful to use the 0...n index.

like image 753
Yada Avatar asked Jul 23 '15 15:07

Yada


2 Answers

You can accomplish this by using getDictionary() on your collection.

Like so:

$users = User::where('created_at', '>=', '2015-01-01')->get()->getDictionary();

Note: in newer version of Laravel (5.2+), getDictionary() was removed; keyBy() can be used instead:

$users = User::where('created_at', '>=', '2015-01-01')->get()->keyBy('id');
like image 73
Francesco de Guytenaere Avatar answered Nov 02 '22 04:11

Francesco de Guytenaere


I created my own solution by having a super Model that extends Eloquent.

Full solution: https://gist.github.com/yadakhov/741173ae893c1042973b

/**
 * Where In Hashed by primary key
 *
 * @param array $ids
 * @return array
 */
public static function whereInHash(array $ids, $column = 'primaryKey')
{
    $modelName = get_called_class();
    $primaryKey = static::getPrimaryKey();
    if ($column === 'primaryKey') {
        $column = $primaryKey;
    }
    $rows = $modelName::whereIn($column, $ids)->get();
    $out = [];
    foreach ($rows as $row) {
        $out[$row->$primaryKey] = $row;
    }
    return $out;
}
like image 23
Yada Avatar answered Nov 02 '22 06:11

Yada