М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
];
}