【发布时间】:2020-04-17 20:35:02
【问题描述】:
我正在构建一个 Laravel 应用程序,人们在其中阅读书籍,也喜欢这本书。
图书资源
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'name' => $this->name,
'about' => $this->about,
'content' => $this->content,
'image' => $this->image_url,
'recommended' => $this->recommended,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'author' => $this->author,
'no_of_pages' => $this->pages,
// 'favorited' => I want o show true or false depending if user favorited
];
}
我想在用户模型中设置包括用户收藏的书,所以如果用户收藏则显示true和false。
通过这样做,我能够在单个书籍模型中做到这一点
public function showapi(Request $request, $book)
{
//$book = Book::find($book);
$book = new BookResource(Book::find($book));
$Fav = Favorite::where('book_id', $book->id)->where('user_id', $request->user_id)->exists();
if($Fav) {
return response()->json([
'book' => $book,
'Favorited' => $Fav,
]
);
}
else
return response()->json([
'book' => $book,
'Favorited' => $Fav,
]
);
}
此设置收藏为真或假
但我想在发送图书收藏时显示收藏夹
我已经尝试通过这样做来使用 Laravel API 资源关系
'item' => FavoriteResource::collection($this->when(Favorite::where('book_id', $this->id)
->where('user_id', $request->user_id), 'item')),
我在使用邮递员测试时遇到了这个错误
在文件中的字符串上调用成员函数 first()
这是我的方法
public function indexapi()
{
return BookResource::collection(Book::with('author')->Paginate(16));
}
这是我的关系
用户模型
public function favorites(){
return $this->hasMany(Favorite::class);
}
public function books()
{
return $this->belongsToMany(Book::class);
}
图书模型
public function favorites()
{
return $this->hasMany(Favorite::class);
}
**最喜欢的模特**
public function book ()
{
return $this->belongsTo(Book::class);
}
public function author()
{
return $this->belongsTo(Author::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
【问题讨论】:
-
用户和图书有什么关系?是多对多吗?
-
用户和图书之间没有关系。我已经更新了我的问题
标签: laravel