繁体   English   中英

从具有多对多关系的不同模型访问访问器

[英]accessing the accessor from different model with many to many relationship laravel

假设我有我的Product模型的accessor

class Product extends Model
{
    public function getIncomeAttribute() { 
        $sub_total = $this->price * $this->quantity; 
        $discount = round((10 / 100) * $sub_total, 2); 
        return round(($sub_total - $discount), 2); 
    }

    public function orders(){
        return $this->belongsToMany(Order::class)->withPivot('quantity')->withTimestamps();
    }
}

我的产品模型与订单有很多关系,这就是我的order model

class Order extends Model
{
    public function products(){
        return $this->belongsToMany(Product::class)->withPivot('quantity')->withTimestamps();
    }
}

从订单中如何访问产品模型中的访问器? 我尝试了这个$this->products->quantity ,但是错误是Property [income] does not exist on this collection instance

这是我的OrderResource ,它扩展了JsonResource ,在这里我尝试使用$this->products->income

public function toArray($request){
    $sub_total= 0;
    foreach($this->products as $product){
        $sub_total += ($product->pivot->quantity * $product->price);
    }
    $discount = round((10 / 100) * $sub_total, 2);
    $total = round(($sub_total - $discount), 2);
    $sub_total = round($sub_total,2);
    return [
        'id' => $this->id,
        'address' => $this->address,
        'sub_total' => $sub_total,
        'discount' => $discount,
        'total_price' => $this->products->quantity,
        'created_at' => Carbon::parse($this->created_at)->format('F d, Y h:i:s A'),
        'customer' => $this->user,
        'items' => ProductsResource::collection($this->products)
      ];
 }

在订单模型中创建分类subTotal访问器

订单模型

public function getSubTotalAttribute() {  //calculate product subtotal 
   $sub_total = 0;

   foreach($this->products as $product){
      $sub_total += ($product->pivot->quantity * $product->price);
   }

   return $sub_total;
}

现在在OrderResource使用它

公共函数toArray($ request){

$discount = round((10 / 100) * $this->subTotal, 2); 

$totalPrice = round(($this->subTotal - $discount), 2); 

return [
    'id' => $this->id,
    'address' => $this->address,
    'sub_total' => $this->subTotal,
    'discount' => $discount,
    'total_price' => $totalPrice,
    'created_at' => Carbon::parse($this->created_at)->format('F d, Y h:i:s A'),
    'customer' => $this->user,
    'items' => ProductsResource::collection($this->products)
  ];

}

注意:提取Order急于加载Product

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM