在 Laravel 中计算多个模型
Count Multiple Models in Laravel
我有多个模型:User、Track、Tutorial、Chapter、Lesson 和 SolvedLesson。
下面是我为计算每个模型所做的工作。
$data = [
'userCount' => \App\User::count(),
'userRegisteredToday' => \App\User::whereCreatedAt(date('Y-m-d'))->count(),
'trackCount' => \App\Models\Track::count(),
'tutorialCount' => \App\Models\Tutorial::count(),
'chapterCount' => \App\Models\Chapter::count(),
'lessonCount' => \App\Models\Lesson::count(),
'solvedLessonCount' => \App\Models\SolvedLesson::count(),
];
Laravel 提供关系和预加载以高效查询。
有什么方法可以将上述查询转换为一个查询以获得更好的性能吗?
withCount 方法允许您计算模型关系的结果数。
假设您已经定义了 User
和 SolvedLesson
模型之间的一对多关系:
// you can optionally alias the appended count attribute
$users = User::withCount('solvedLessons as solved_count')->get();
// total users
$users->count()
// iterate users to get the number of solved lessons for each
$users->each(function (User $user) {
// using the alias defined above
echo $user->solved_count;
});
您也不限于单个关系,传递数组将获得每个关系的计数:
$tracks = Track::withCount(['tutorials', 'users'])->get();
// total tracks
$tracks->count()
// access each relation count per track
$tracks->each(function (Track $track) {
echo $track->tutorial_count;
echo $track->user_count;
});
我有多个模型:User、Track、Tutorial、Chapter、Lesson 和 SolvedLesson。
下面是我为计算每个模型所做的工作。
$data = [
'userCount' => \App\User::count(),
'userRegisteredToday' => \App\User::whereCreatedAt(date('Y-m-d'))->count(),
'trackCount' => \App\Models\Track::count(),
'tutorialCount' => \App\Models\Tutorial::count(),
'chapterCount' => \App\Models\Chapter::count(),
'lessonCount' => \App\Models\Lesson::count(),
'solvedLessonCount' => \App\Models\SolvedLesson::count(),
];
Laravel 提供关系和预加载以高效查询。 有什么方法可以将上述查询转换为一个查询以获得更好的性能吗?
withCount 方法允许您计算模型关系的结果数。
假设您已经定义了 User
和 SolvedLesson
模型之间的一对多关系:
// you can optionally alias the appended count attribute
$users = User::withCount('solvedLessons as solved_count')->get();
// total users
$users->count()
// iterate users to get the number of solved lessons for each
$users->each(function (User $user) {
// using the alias defined above
echo $user->solved_count;
});
您也不限于单个关系,传递数组将获得每个关系的计数:
$tracks = Track::withCount(['tutorials', 'users'])->get();
// total tracks
$tracks->count()
// access each relation count per track
$tracks->each(function (Track $track) {
echo $track->tutorial_count;
echo $track->user_count;
});