Laravel 显示有枢轴 table 错误的图书类别

Laravel showing the categories of book with pivot table error

我正在学习 Laravel 并且我有两本 table 书籍和类别 我用 book_id 和 category_id 列创建了一个枢轴 table 来建立 table 之间的关系,但是当我试图在展示书页中显示类别时我在 $books->categories 上创建了 foreach 我遇到了一个错误,指出 foreach 参数为 null

书籍模型文件:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'desc', 'img'];

    public function categories()
    {
        return $this->belongsTo('App\Models\Category');
    }
}

类别模型文件

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;
    
    protected $fillable = ['name'];

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

show.blade 页面:

@extends('layout')

@section('title')
    Book #{{ $book->id }}
@endsection

@section('content')
    <h2>{{ $book->title }}</h2>
    <p>{{ $book->desc }}</p>
    @foreach ($book->categories as $category)
        <span class="text-muted mx-3">{{ $category->name }}</span>
    @endforeach
    <div class="row">
        <div class="col-md-3 p-5">
            <img src="{{ asset('uploads/books') }}/{{$book->img}}" class="w-100">
        </div>
    </div>
    <a href="{{ route('books.index') }}" class="btn btn-primary">Back</a>
    <a href="{{ route('books.edit', $book->id) }}" class="btn btn-warning mx-2">Edit</a>
    <a href="{{ route('books.delete', $book->id) }}" class="btn btn-danger">Delete</a>
@endsection

支点table:

the pivot table

BookController 代码:

public function show($id)
    {
        $book = Book::findOrFail($id);

        return view('books/show', compact('book'));
    }

您可以将关系更改为 belongsToMany,因为您正在使用数据透视 table。

书中模型

public function categories()
{
    return $this->belongsToMany(Category::class);
}

并在 Category 模型中

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

在你的控制器中

  $book = Book::with('categories')->findOrFail($id);

所以在你看来

{{$book->$title}}
@foreach ($book->categories as $category)
    <span class="text-muted mx-3">{{ $category->name }}</span>
@endforeach