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->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);
}
我已经这样做了,这对我不起作用,因为我不知道我做错了什么。谢谢。
解决方案
拥有后,您可以通过查询字段$book
轻松加载同一作者的其他书籍。author_id
只要确保从查询中排除原书,就可以了。
$relatedBooks = Book::where('author_id', $book->author_id)
->where('id', '!=', $book->id)
->get();
作为旁注,您已经在方法参数中传递了 Book 的实例,因此代码的第一行 ( $book = Book::where('id', '=', $book)->first();
) 是多余的,您可以简单地使用$book
.
推荐阅读
- c# - 如何使用 Controls.PrintDialog,通过 PrintVisual() 或 PrintDocument() 打印
- php - 如何在嵌套数组中添加数组(PHP Mongodb)
- spring-integration - Spring集成Logging消息通道ID
- java - 使用流基于另一个列表更新一个列表
- java - NXP NFC NDEF 标签内存大小问题
- abap - 在 UDM_DISPUTE 中检索模板时缓存的值
- javascript - webpack-dev-server 热重载不起作用?
- python - python 3 txt文件数字签名和验证
- angular - Angular 6 事件发射器 - 不起作用
- batch-file - 在批处理文件中将变量传递给 cURL