簡體   English   中英

將 foreach for toarray 添加到 Laravel REST API 中的 JsonResource

[英]Add foreach for toarray to a JsonResource in Laravel REST API

我為每部電影收集了一系列類型,我想在 api 請求中顯示每部電影的每一部。 這是資源:

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'status' => $this->status,
            'image_path' => url()->to('/images/' .$this->image_path),
            'genres' => ''
        ];
    }

我相信我需要在 Movie 模型中訪問流派並在 toarray 函數中使用 foreach 但是應該如何完成呢? 這是我的遷移:

    public function up()
    {
        Schema::create('genres', function (Blueprint $table) {
            $table->id();
            $table->string('name');
        });
    }

    public function up()
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('status')->nullable()->default(0);
            $table->string('image_path')->default('default.png');
        });
    }

    public function up()
    {
        Schema::create('genre_movie', function (Blueprint $table) {
            $table->foreignId('genre_id')->constrained()->cascadeOnDelete();
            $table->foreignId('movie_id')->constrained()->cascadeOnDelete();
        });
    }

電影型號:

class Movie extends Model
{
    use HasFactory;

    public $timestamps = false;
    protected $fillable = ['name', 'status', 'image_path'];

    public function genres()
    {
        return $this->belongsToMany(Genre::class, 'genre_movie');
    }
}

流派型號:

class Genre extends Model
{
    use HasFactory;

    public $timestamps = false;
    protected $fillable = ['name'];

    public function movies()
    {
        return $this->belongsToMany(Movie::class, 'genre_movie');
    }
}

控制器中的功能:

    public function index()
    {
        return MovieResource::collection(Movie::paginate());
    }

創建流派資源。

class GenreResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'name' => $this->name,
        ];
    }
}

使用with()將其加載到控制器中。

public function index()
{
    $movies = Movie::with('genres')->paginate();

    return MovieResource::collection();
}

將它添加到MovieResource ,使用whenLoaded()和一個閉包,所以如果它沒有加載,你就不必顯示它。

public function toArray($request)
{
    return [
        ...
        'genres' => $this->whenLoaded('genres', function () {
            return GenreResource::collection($this->genres);
        }),
    ];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM