简体   繁体   中英

Laravel average of numbers per group

For my project, I want students to see the average grade per school subject.

$grades = Auth::user()->student->grades()
    ->with('subject')->orderByDesc('created_at')
    ->get()->groupBy('subject_id');

Now I first get the grades with the subject and then group them by subject. How can I add the average grade per subject group?

Table columns

在此处输入图像描述

The simplest would be to select all rows with subject id X, loop through and and add all the scores to a total, then divide that total by the count() of the rows returned.

A nicer way might be through crafting a cool SQL query that does the same, but that's for you to decide, this is roughly how you do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM