首页 > 解决方案 > 在 Laravel 中返​​回相关书籍

问题描述

我想退回与使用作者姓名的书籍相关的书籍

我的控制器中有这个功能

public function show(Book $book) {

        $book = Book::where('id', '=', $book)->first();
        $related = Book::whereHas('author_id', function ($q) use ($book) {
        return $q->whereIn('name', $post->author->pluck('id')); 
        })
        ->where('id', '!=', $book->id) // So I won't fetch same post
        ->get();
        return view('book')
        ->with($book)
        ->with($related); 
}

这就是我的book table样子

public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->text('about');
        $table->string('image');  
        $table->string('image_url');
        $table->string('epub_url');
        $table->integer('author_id'); 
        $table->string('publisher');  
        $table->year('year');
        $table->boolean('recommended')->default(0);
        $table->timestamps();    
    });
}

我在我的模型中做到了这一点

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

Book模型中

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

我已经这样做了,这对我不起作用,因为我不知道我做错了什么。谢谢。

标签: laravel

解决方案


拥有后,您可以通过查询字段$book轻松加载同一作者的其他书籍。author_id只要确保从查询中排除原书,就可以了。

$relatedBooks = Book::where('author_id', $book->author_id)
  ->where('id', '!=', $book->id)
  ->get();

作为旁注,您已经在方法参数中传递了 Book 的实例,因此代码的第一行 ( $book = Book::where('id', '=', $book)->first();) 是多余的,您可以简单地使用$book.


推荐阅读