簡體   English   中英

如何使用資源集合 Laravel 傳遞嵌套數組的第一個元素

[英]How to pass first element of nested array using resource collection Laravel

Мy Controller

    public function index()
    {
          return AdvertResource::collection(Advert::with('image')
              ->paginate(10));
    }

廣告模型中的方法image

    public function image()
    {
        return $this->hasMany(AdvertImage::class);
    }

Мy AdvertResource

    public function toArray($request)
    {
        return [
            'title' => $this->title,
            'price' => $this->price,
            'image' => AdvertImgResource::collection($this->image),
            'created_at' => $this->created_at
        ];
    }

Мy AdvertImgResource

    public function toArray($request)
    {
        return [
            'path' => $this->path,
        ];
    }

The data I receive

        {
            "title": "title",
            "price": 500,
            "image": [
                {
                    "path": "img1"
                    "path": "img2"
                    "path": "img3"
                }
            ],
            "created_at": "2022-07-14T18:14:37.000000Z"
        },

每個廣告有幾張照片,我需要顯示主照片(列表中的第一張)你能告訴我是否可以顯示每個對象的路徑數組的第一個元素? 它也應該在 index 方法中,因為在 show 方法中我會完整獲取所有元素。

我認為可以通過向 AdvertImgResource 中的返回數組添加一個新值來完成,如下所示:

//AdvertResource
public function toArray($request)
{
    $images = AdvertImgResource::collection($this->image); //Retrieve image collection here to access the first image in the array.

    return [
        'title' => $this->title,
        'price' => $this->price,
        'image' => $images,
        'first_image' => $images->first(), //Retrieves the first image or returns null if the images collection is empty.
        'created_at' => $this->created_at
    ];
}

暫無
暫無

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

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