我正在使用 Laravel 構建一個 REST API。我的數據庫有一個名為容器的表。Container 與另一個名為 Shop 的表具有外部關系。最后有一個 Image 表,它具有 Shop 表的外鍵。我想為我的容器創建一個端點,它將返回容器數據,包括分配給它的商店的數據以及分配給商店的所有圖像。這是我的容器資源:class Container extends JsonResource{ public function toArray($request) { return [ 'id' => $this->id, 'shop_id' => $this->shop_id, 'shop' => (new ShopResource($this->whenLoaded('shop'))) ]; }}這是我的商店資源:class Shop extends JsonResource{ public function toArray($request) { return parent::toArray($request); }}這是我的容器控制器:class ContainerController extends Controller{ public function index() { return ContainerResource::collection(Container::with('shop')->get()); }}基本上在 Django 中,我所要做的就是將 related_name 分配給 Image 模型(例如,related_name="images"),然后我將使用例如在我的數據庫中獲取與商店模型相關的所有圖像。Shop.objects.first().images 將在 Containers Serializer 中考慮。如何使用 Laravel Rest API 達到同樣的效果?
1 回答

Smart貓小萌
TA貢獻1911條經驗 獲得超7個贊
急切地加載關系。
Container::with('shop.images');
對于我所知道的parent::toArray()應該包括圖像中ShopResource,如果沒有填寫與完成類似的資源ContainerResource。
class Shop extends JsonResource
{
public function toArray($request)
{
return [
...
'images' => ImageResource::collection($this->whenLoaded('images')),
];
}
}
要急切加載多個關系,使用 with 方法,它也可以采用數組。
Container::with(['shop.images', 'shop.employees',]);
- 1 回答
- 0 關注
- 93 瀏覽
添加回答
舉報
0/150
提交
取消