Laravel 归还拉雷维尔的相关书籍
我想归还一本与使用作者姓名的书相关的书 我的控制器中有这个功能Laravel 归还拉雷维尔的相关书籍,laravel,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->
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);
}
这就是我的图书表的样子
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);
}
在手册中
型号
public function author()
{
return $this->belongsTo(Author::class);
}
我已经这样做了,这对我来说不起作用,因为我不知道我做错了什么。谢谢。你问错了方向。你能做的就是先拿到书的作者
$book = Book::with(['author'])->where(['id' => $BOOK_ID])->first();
然后,您可以加载来自相同作者的类似书籍
$similarBooks=Book::whereHas('author'=>函数($query)use($Book){
$query->where(['id'=>$book->author->id]);
})->其中('id','!=',$book->id)->get();
或者,您可以通过替换关系的查询按作者姓名加载。一旦您拥有了$book
,您可以通过查询作者id
字段轻松加载同一作者的其他书籍。只要确保从查询中排除原始图书,就可以开始了
$relatedBooks = Book::where('author_id', $book->author_id)
->where('id', '!=', $book->id)
->get();
顺便说一句,您已经在方法参数中传递了Book的实例,因此代码的第一行($Book=Book::where('id','=',$Book)->first();
)是多余的,您只需从show
方法获取Book
对象的位置使用$Book
?我认为这应该像《代码》节目($book)
一样。如果您有stackTrace,请将其发布在此返回的未定义变量:BOOK\u ID
将BOOK\u ID替换为您拥有的BOOK ID,如$BOOK->ID,