Last active
January 25, 2020 04:02
-
-
Save n1215/c9a2925285adfdde30f2008ff06e21bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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, | |
]; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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