在Laravel中计算多个模型

时间:2019-01-04 04:47:30

标签: php laravel eloquent laravel-query-builder

我有多个模型:用户,跟踪,教程,章节,课程和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提供关系并渴望加载以进行有效查询。 有什么方法可以将上述查询转换为一个查询以获得更好的性能?

1 个答案:

答案 0 :(得分:0)

通过withCount方法,您可以计算模型关系的结果数。

假设您已经定义了UserSolvedLesson模型之间的一对多关系:

// 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;
});