В моем 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": 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();
});