首页 > 解决方案 > 如何在控制器方法中使用与关系模型参数?

问题描述

通常我可以 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没有调用模型类的关系?

标签: phplaravellaravel-7

解决方案


您已经加载了模型,因此您只需要加载关系。这称为延迟加载

public function show(CustomerAddress $address)
{
    return $address->load("province", "city", "postalcode", "district");
}

希望有帮助:)


推荐阅读