![](/img/trans.png)
[英]Laravel Eloquent: How do I refactor this eager load query into model scope method?
[英]How To Eager load a Method in model
我有一個product
model 有一個返回product
price
的方法
public function ProductSeller()
{
return $this->hasMany('App\ProductSeller','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;
}
問題是我想急切地加載它並獲得像$product->price
price
的價格,但我得到App\Product::price must return a relationship instance
。
有人可以幫我嗎?
您想要實現的目標可以通過訪問器完成,很高興您已經完成了一半的步驟。 只需按照 Laravel 的訪問器命名約定在 model 中更改方法的名稱,如下所示:
public function ProductSeller()
{
return $this->hasMany('App\ProductSeller','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;
注意:在 model 中,get() function 從關系的末尾被刪除,並且在 GetPriceAttribute() 方法中調用關系方法時不添加括號。 這種方法對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.