Skip to content

Instantly share code, notes, and snippets.

@n1215
Last active January 25, 2020 04:02
Show Gist options
  • Save n1215/c9a2925285adfdde30f2008ff06e21bc to your computer and use it in GitHub Desktop.
Save n1215/c9a2925285adfdde30f2008ff06e21bc to your computer and use it in GitHub Desktop.
<?php
// EloquentのEager Loadを無理やり使うバージョン
/** @var \Illuminate\Support\Collection<\stdClass> $userAndPoints */
$userAndPoints = Status::query()
->with('user.userDetail')
->select('user_id')
->selectRaw('sum(point) As point')
->groupBy('user_id')
->get()
->map(function (Status $statusModoki) {
// ここの$statusModokiはEloquent Modelがゆるいので許されるが、概念としてはおかしい
return (object) [
'user_id' => $statusModoki->user_id,
'user' => $statusModoki->user,
'point' => $statusModoki->point,
];
});
<?php
// 手動でEager Load相当の処理をするバージョン
/** @var \Illuminate\Support\Collection<\stdClass> $userStatusAggregations */
$userStatusAggregations = Status::query()
->select('user_id')
->selectRaw('sum(point) As point')
->groupBy('user_id')
->toBase()
->get();
/** @var \Illuminate\Database\Eloquent\Collection<User> $users */
$userMap = User::query()
->with('userDetail')
->findMany($userStatusAggregations->map->user_id)
->mapWithKeys(function (User $user) {
return [$user->id => $user];
});
/** @var \Illuminate\Support\Collection<\stdClass> $userAndPoints */
$userAndPoints = $userStatusAggregations
->map(function (\stdClass $statusAggregation) use ($userMap) {
return (object) [
'user_id' => $statusAggregation->user_id,
'user' => $userMap[$statusAggregation->user_id],
'point' => $statusAggregation->point,
];
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment