通常我可以用來 CustomerAddress::with(["province", "city", "district"]);包含與響應的關系,但我使用模型作為方法參數,如下所示:public function show(CustomerAddress $address){ return $address;}目前,我可以使用以下方式獲取關系查詢:public function show(CustomerAddress $address){ $address = CustomerAddress::with(["province", "city", "postalcode", "district"])->where("id", $address->id)->firstOrFail(); return $address;}但我認為這會產生雙重查詢,這對性能不利。我的另一個解決方案是不要在參數中調用模型,如下所示:public function show($address_id){ $address = CustomerAddress::with(["province", "city", "postalcode", "district"])->where("id", $address_id)->firstOrFail(); return $address;}但由于某種原因,我需要CustomerAddress在方法參數中使用模型。是否還有其他解決方案可以包含關系而$address無需再次調用模型類?
2 回答

哈士奇WWW
TA貢獻1799條經驗 獲得超6個贊
您已經加載了模型,因此只需加載關系即可。這稱為延遲預加載。
public?function?show(CustomerAddress?$address){ ????return?$address->load("province",?"city",?"postalcode",?"district"); }
希望有幫助:)

呼如林
TA貢獻1798條經驗 獲得超3個贊
顯示方法是這樣的
public function show(CustomerAddress $address) { return $address::with(["province", "city", "postalcode", "district"])->where("id", $address->id)->firstOrFail(); }
您可以使用 show 方法并傳遞CustomerAddress
as 參數
show(new CustomerAddress())
- 2 回答
- 0 關注
- 152 瀏覽
添加回答
舉報
0/150
提交
取消