[英]How to get fields from related tables with Eloquent PHP laravel?
[英]How to get only specific fields from Laravel Eloquent API Resource?
我正在開發一個 API,它可以通過手機和 web 應用程序訪問。
我需要從 API 資源中發送特定字段。
我有ItemResource
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'price' => $this->price,
'stock' => $this->stock,
'reviews' => $this->reviews, // this is from reviews table
];
}
我的Item
Model
public function reviews() {
return $this->hasMany(ItemReview::class);
}
我的 controller 代碼
return ItemResource::collection(Item::all());
我得到這個數組
{
"data": {
"id": 10,
"name": "Item Name",
"description": "Item description",
"price": 410,
"stock": "815",
"reviews": [
{
"id": 4, // I don't want to get this field
"item_id": 10, // I don't want to get this field
"user_id": 9, // I want to show user name instead of user id
"review": "item review."
},
{
"id": 12, // I don't want to get this field
"item_id": 10, // I don't want to get this field
"user_id": 3, // I want to show user name instead of user id
"review": "item review."
}
]
}
}
我想得到一個這樣的數組
{
"data": {
"id": 10,
"name": "Item Name",
"description": "Item description",
"price": 410,
"stock": "815",
"reviews": [
{
"user_name": 'jhon',
"review": "item review."
},
{
"user_name": 'jhon2',
"review": "item review."
}
]
}
}
我只想顯示特定的字段。
我該如何實施?
select
如果您在reviews
后添加括號,您可以返回一個Builder
實例,這將允許您向關系添加查詢。
有了這個,您可以select
您需要的字段。
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'price' => $this->price,
'stock' => $this->stock,
'reviews' => $this->reviews()->select('user_name', 'review')->get(),
];
}
ReviewResource
您還可以為Review
創建返回其自己數據的資源。
class ReviewResource extends JsonResource
{
public function toArray($request)
{
return [
'user_name' => $this->user_name,
'review' => $this->review,
];
}
}
class ItemResource extends JsonResource
{
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'price' => $this->price,
'stock' => $this->stock,
'reviews' => ReviewResource::collection($this->reviews),
];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.