如何在模型中加载方法



我有一个product模型,它有一个返回productprice的方法

public function ProductSeller()
{
return $this->hasMany('AppProductSeller','product_id')->get();
}
public function price()
{
$productSellers = $this->ProductSeller();
foreach ($productSellers as $productSeller){
$productPrice[]=$productSeller->price;
}
if (empty($productPrice) == true || min($productPrice) == '0'){
$Rprice = 'call for price';
} else {
$Rprice = number_format(min($productPrice));
}
return $Rprice;
}

问题是我想急于加载它,并获得price$product->price,但我得到AppProduct::price must return a relationship instance

有谁能帮我一下吗?

您可以通过访问来实现。令人高兴的是,你已经完成了一半的步骤。只需按照Laravel的访问器命名约定更改模型中的方法名称,如下所示:

public function ProductSeller()
{
return $this->hasMany('AppProductSeller','product_id');
}

public function GetPriceAttribute()
{
$productSellers = $this->ProductSeller;
foreach ($productSellers as $productSeller){
$productPrice[]=$productSeller->price;
}
if (empty($productPrice) == true || min($productPrice) == '0'){
$Rprice = 'call for price';
} else {
$Rprice = number_format(min($productPrice));
}
return $Rprice;
}
现在,您可以轻松地访问如下方法:
$product->price;

注意:在模型中,get()函数从关系的末尾删除,并且在调用关系方法时没有在GetPriceAttribute()方法中添加括号。这个方法对我来说很有效。

最新更新