如何在控制器方法中使用与模型参数的关系?
How to use with relationship to model param in controller method?
通常我可以使用 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
的关系而无需再次调用模型 class?
这样的展示方式
public function show(CustomerAddress $address) {
return $address::with(["province", "city", "postalcode", "district"])->where("id", $address->id)->firstOrFail();
}
您可以使用 show 方法并将 CustomerAddress
作为参数传递
show(new CustomerAddress())
您已经加载了模型,所以您只需要加载关系。这叫做lazy eager loading.
public function show(CustomerAddress $address)
{
return $address->load("province", "city", "postalcode", "district");
}
希望对您有所帮助:)
通常我可以使用 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
的关系而无需再次调用模型 class?
这样的展示方式
public function show(CustomerAddress $address) {
return $address::with(["province", "city", "postalcode", "district"])->where("id", $address->id)->firstOrFail();
}
您可以使用 show 方法并将 CustomerAddress
作为参数传递
show(new CustomerAddress())
您已经加载了模型,所以您只需要加载关系。这叫做lazy eager loading.
public function show(CustomerAddress $address)
{
return $address->load("province", "city", "postalcode", "district");
}
希望对您有所帮助:)