仅获取 Eloquent 中指定 ID 的结果

Getting result only for a specified id in Eloquent

我有个小问题。我的代码可以正常工作,但我认为我没有以正确的方式进行。

在我的 GradeController 中我有这个代码:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    if(auth()->user()->hasRole('Student')) {
        $subjects = Subject::all();

        return view('grades.student.index', compact('subjects'));
    }
}

在我看来,我通过这种方式获得了属于指定用户的成绩:

@foreach($subject->grades->where('student_id', '=', auth()->user()->id) as $grade)
<span class="badge badge-primary">
    {{ $grade->value }}
</span>@endforeach

在这里,我的意思是Laravel,还有更好的方法吗?因为我认为获取属于一个主题的所有成绩然后查找 ID 不是很 "effective"。

祝你有美好的一天。

您可以使用 with() 预加载帮助程序,使用闭包根据属于已登录用户的成绩过滤 subject 的“成绩”:

$subjects = Subject::with(['grades' => function($query) {
    $query->where('student_id', auth()->user()->id);
}])->get();

请注意删除 ->where() 子句中的 , '=',。如果检查是否等于,则不需要此参数。

在你的控制器中index()你可以制作一个中间件而不是多次检查auth()->user()->hasRole('Student'),如果你在这里只检查一次就买好了。

public function index()
{
    // refactoring 
    return view('grades.student.index', ['subject' => Subject::all()]);
}

在你的 blade 文件中进行查询也不好,所以你可以直接从你的控制器 grades 传递

public function index()
{
    return view('grades.student.index', [
        'grades' => Grade::where('student_id', auth()->id())->get()
    ]);
}

index blade 文件中,您现在可以使用:


@foreach($grades as $grade)
<span class="badge badge-primary">
    {{ $grade->value }}
</span>
// you can get the subject from $grade->subject
@endforeach