Laravel Eloquent get() 由主键 id 索引

Laravel Eloquent get() indexed by primary key id

我经常发现通过主键 id 索引我的结果非常有用。

示例:

$out = [];

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

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

return $out;

有没有办法用 Eloquent 一次性做到这一点?使用 0...n 索引没有用。

不适用于 eloquent,但这可能是比遍历所有结果更好的选择。

$users = Users::all();

return array_combine($users->modelKeys(), $users);

我通过扩展 Eloquent.

的超级模型创建了自己的解决方案

完整解决方案: 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;
}

您可以通过在 collection 上使用 getDictionary() 来完成此操作。

像这样:

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

注意:在较新版本的 Laravel (5.2+) 中,getDictionary() 已被删除;可以用keyBy()代替:

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

你可以使用keyBy()

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