【问题标题】:Nested API Resource in LaravelLaravel 中的嵌套 API 资源
【发布时间】:2020-02-11 02:58:18
【问题描述】:

在我的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 tableUserBook 之间的数据透视表

在我的书桌上,我有这个

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();
});

【问题讨论】:

    标签: laravel


    【解决方案1】:

    我通过像这样返回我的 FavoriteResource 来修复它

    public function toArray($request)
    {
        return [
         //'book_id' => $this->book,
         'book_id' => new BookResource($this->book),
            'user_id' => $this->user_id,
       ];    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 2016-12-30
      • 2019-04-30
      • 1970-01-01
      • 2017-12-17
      相关资源
      最近更新 更多