Laravel 无法在列表中显示 foreign

我正在 laravel 中创建学生和书籍的一对一关系。 我无法在主页中显示外部变量。 我想在学生的索引页中显示书名。 我如何在视图中调用它?

Student Table

Schema::create('students', function (Blueprint $table) {
    $table->id();
    $table->string('name');

     // define foreign key
     $table->foreignId('book_id')
     ->nullable()
     ->constrained()
     ->onUpdate('cascade')
     ->onDelete('cascade');


    $table->timestamps();
});

Book Model

class Book extends Model{


protected $fillable = [
    'name','description' 
 ];
 
 public function students(): HasOne
 {
     return $this->hasOne(Student::class, 'book_id', 'id');
 } }

Student Model

class Student extends Model{
protected $fillable = [
    'book_id','name' 
 ];


 public function books(){
    return $this->belongsTo(Book::class);
}}

Student Controller

public function index(){
    $students = Student::select('id', 'name')->latest()->orderByDesc('id')->paginate(3);
    $books = Book::all();
    return view('students.index', compact('students', 'books',));
 }

模板

@foreach($students as $student)
   <tr>
      <td>{{ $student->id }}</td>
      <td>{{ $student->book_id }}</td>
      <td>{{ $student->name }}</td>
      <td>
           <!-- Edit -->
         <a href="{{ route('students.show',[$student->id]) }}" class="btn btn-sm btn-primary">Show</a>
         <!-- Edit -->
         <a href="{{ route('students.edit',[$student->id]) }}" class="btn btn-sm btn-info">Edit</a>
         <!-- Delete -->
         <a href="{{ route('students.delete',$student->id) }}" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this student?')">Delete</a>
      </td>
   </tr>
@endforeach
回答
L
Lue Blanda III
3周前

您将查询限制为仅选择 id 和 name,因此查询不会返回 book_id。 只需删除选择(在分页情况下无用)

public function index(){
    $students =    Student::query()->with('books')->latest()->orderByDesc('id')->paginate(3);
    $books = Book::all();
    return view('students.index', compact('students', 'books',));
}

然后在您的视图中,您可以显示 book_id 或直接显示书名

@foreach($students as $student)
   <tr>
      <td>{{ $student->id }}</td>
      <td>{{ $student->book_id }}, {{ $student->books->name }}</td>
      <td>{{ $student->name }}</td>
      <td>
           <!-- Edit -->
         <a href="{{ route('students.show',[$student->id]) }}" class="btn btn-sm btn-primary">Show</a>
         <!-- Edit -->
         <a href="{{ route('students.edit',[$student->id]) }}" class="btn btn-sm btn-info">Edit</a>
         <!-- Delete -->
         <a href="{{ route('students.delete',$student->id) }}" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this student?')">Delete</a>
      </td>
   </tr>
@endforeach