You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel/Eloquent技术问询:如何查询当前用户关联的成绩单

Retrieve and Display a User's Transcripts in a School Management System

Hey there! Since you’ve already set up the hasMany/belongsTo relationships between your User and Transcript models, you’re halfway there. Let’s break down how to pull the data and display it cleanly with Blade.

Step 1: Fetch the User's Transcripts in Your Controller

First, you’ll need to grab the currently authenticated user’s transcripts using the relationship you defined. Here’s how to do it in your controller method:

// Import the Auth facade at the top of your controller if you haven't already
use Illuminate\Support\Facades\Auth;

public function showTranscripts()
{
    // Get the current user's transcripts via the relationship
    // Replace 'transcripts' with whatever you named your hasMany method in the User model
    $transcripts = Auth::user()->transcripts;

    // Pass the transcripts data to your Blade view
    return view('transcripts.show', compact('transcripts'));
}

A quick optimization tip: If you want to avoid the N+1 query problem (especially useful if you add more related data later), eager load the transcripts upfront:

$user = Auth::user()->with('transcripts')->first();
$transcripts = $user->transcripts;

Step 2: Display the Data in a Blade View

Now that you’ve passed the $transcripts variable to your view, you can build a table to show the details. Here’s a simple example Blade template:

<div class="container">
    <h1>Your Transcripts</h1>
    <table class="table">
        <thead>
            <tr>
                <th>Course Name</th>
                <th>Grade</th>
                <th>Semester</th>
                <th>Date Issued</th>
            </tr>
        </thead>
        <tbody>
            @foreach($transcripts as $transcript)
                <tr>
                    <td>{{ $transcript->course_name }}</td>
                    <td>{{ $transcript->grade }}</td>
                    <td>{{ $transcript->semester }}</td>
                    <td>{{ $transcript->issued_at->format('M d, Y') }}</td>
                </tr>
            @empty
                <tr>
                    <td colspan="4" class="text-center">No transcripts found for your account.</td>
                </tr>
            @endempty
        </tbody>
    </table>
</div>

Quick Reminders:

  • Double-check that column names (like course_name, grade) match exactly what’s in your transcripts database table.
  • If your User model’s relationship method isn’t named transcripts, swap that out for your actual method name (e.g., reportCards if that’s what you used).
  • Don’t forget to add a route pointing to your controller method so users can access this page!

内容的提问来源于stack exchange,提问作者Julles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:59:18