php - 如何在控制器方法中使用与关系模型参数?
问题描述
通常我可以 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
没有调用模型类的关系?
解决方案
您已经加载了模型,因此您只需要加载关系。这称为延迟加载。
public function show(CustomerAddress $address)
{
return $address->load("province", "city", "postalcode", "district");
}
希望有帮助:)
推荐阅读
- flask - 错误:saml2.client_base:XML 解析错误:不适合我!!!在使用 haproxy 的 flask_saml 实现中
- azure-iot-edge - 通过边缘运行时模块访问 SMB 文件共享(不带 blob 存储模块)
- ios - Apple 移动产品类型常量,例如“Watch4,4”
- algorithm - Vue.js Dijkstra 算法的性能问题
- javascript - javascript获取网页的最新副本
- javascript - 在新的位置更改时更新地图上的标记位置 - 反应原生
- java - 如何将字符串从适配器传递给 Activity 到 Fragment 然后再传递给 Activity
- css - 网页缓存导致我为不同网页设置的背景图片被清空后才可以替换怎么办?
- html - 导航不显示
- c# - 从c#恢复sql数据库