在我的Favorite Resource
中,我有这个
public function toArray($request)
{
return [
'book_id' => $this->book,
// 'book_id' => BookResource::collection($this->whenLoaded('book_id')),
'user_id' => $this->user_id,
];
}
但是当我向我的终端节点发送请求时
{
"book_id": {
"id": 2,
"name": "fcdsadxa",
"about": "xzxzxZ",
"image_url": "#.png",
"epub_url": "#.epub",
"author_id": 1,
"publisher": "dss",
"year": 1990,
"recommended": 1,
"created_at": "2019-12-07 07:44:51",
"updated_at": "2019-12-07 07:44:51",
"pages": null
},
有没有办法返回作者的详细信息,而不仅仅是如下所示的ID
"id": 1,
"name": "Dragon and Box",
"about": "dss",
"content": null,
"image": "h#.png",
"recommended": 0,
"created_at": "2019-12-07T07:44:51.000000Z",
"updated_at": "2019-12-07T07:44:51.000000Z",
"author": {
"id": 1,
"name": "Odutola Abisoye",
"about": "dsfcds",
"image_url": "#.png",
"created_at": "2019-12-07 07:44:06",
"updated_at": "2019-12-07 07:44:06"
},
由于favorite table
是介于User
和Book
之间的数据透视表
在我的书表中,我有这个
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('about');
$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 book ()
{
return $this->belongsTo(Book::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
书籍模型
public function favorites()
{
return $this->hasMany(Favorite::class);
}
用户模型
public function favorites()
{
return $this->hasMany(Favorite::class);
}
这是我最喜欢的架构的样子
Schema::create('favorites', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('book_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
我通过像这样返回我的收藏夹资源来修复它
public function toArray($request)
{
return [
//'book_id' => $this->book,
'book_id' => new BookResource($this->book),
'user_id' => $this->user_id,
];
}