Laravel 无法显示关系名称而不是 id,即使定义为关系

Laravel not able to display relationship name instead of id, even though defined as relation

我在我的 Laravel 应用程序中定义了书籍和作者之间的关系,如下所示:

我的图书型号:

class Book extends Model
{
    use HasFactory;

    protected $table = 'books';

    protected $fillable = [
        'ISBN', 'publisher_id', 'author_id', 'year', 'title', 'price',
    ];

    public function author()
    {
        return $this->belongsTo(Author::class);
    }
}

这是我的 BookController 索引:

public function index()
{
    return view('books.index', [
        'books' => DB::table('books')->paginate(15)
    ]);
}

所以现在我想在我的视图中显示作者姓名而不是 author_id:

@foreach ($books as $book)
    <tr>
        <td>{{ $book->author->name }}</td>
    </tr>
@endforeach

但我一直收到错误消息:

Undefined property: stdClass::$author (View: index.blade.php)
'books' => DB::table('books')->paginate(15)

当您使用 db 时,您处理的是查询生成器,而不是 eloquent 查询生成器!

您必须使用模型本身并加载关系:

'books' => Book::with(['author'])->paginate(15);