如何在Laravel中合并具有相同用户ID的集合并获得他的平均成绩

时间:2018-02-16 08:57:57

标签: laravel

我需要在Laravel中合并具有相同用户ID的集合并获得他的平均成绩,因为现在我的应用程序显示两个记录而不是一个如果他有2个等级并且我想以某种方式解决这个问题..这是我的laravel代码:

@foreach($grades->sortByDesc('grade')->take(10) as $grade)
    <div class="row">
        <div class="col-md-9">
            @if($grade->user_id == Auth::id())
                <strong>{{ $grade->user->first_name . " " . $grade->user->last_name }}</strong>
            @else
                ...
            @endif
        </div>

        <div class="col-md-3">{{ round($grade->where('user_id', $grade->user_id)->where('module_id', $module->id)->avg('grade'), 2) }}</div>
    </div>
@endforeach

所以我想要这个结果:

enter image description here

而不是:

enter image description here

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

使用groupBy()

@foreach ($grades->sortByDesc('grade')->take(10)->groupBy('user_id') as $userGrades)
    <div class="row">
        <div class="col-md-9">
            @if($grade->user_id == Auth::id())
                <strong>{{ $userGrades->first()->user->first_name . ' ' . $userGrades->first()->user->last_name }}</strong>
            @else
                ...
            @endif
        </div>

        <div class="col-md-3">{{ round($userGrades->where('module_id', $module->id)->avg('grade'), 2) }}</div>
        </div>
    </div>
@endforeach

或者您可以加载具有成绩的用户:

$users = User::with('grades')->get();

然后:

@foreach ($users as $user)
    {{ $user->grades->avg('grade') }}
@endforeach