php Laravel无法在列表中显示foreign

rn0zuynd  于 2023-05-05  发布在  PHP
关注(0)|答案(1)|浏览(175)

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

学生桌

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();
    });

图书型号

class Book extends Model{

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

学生模型

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

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

学生控制器

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
ux6nzvsh

ux6nzvsh1#

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

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

相关问题