亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP Laravel REST api 雙反關系

PHP Laravel REST api 雙反關系

PHP
侃侃無極 2022-10-22 16:47:04
我正在使用 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',]);


查看完整回答
反對 回復 2022-10-22
  • 1 回答
  • 0 關注
  • 93 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號