accessing the accessor from different model with m

2019-08-29 00:58发布

Supposed i have an accessor to my Product model

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();
    }
}

My product model has a many to many relationship with order, this is my order model

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

from my order how can i access the accessor in my product model? i tried this $this->products->quantity, but the error is Property [income] does not exist on this collection instance

this is my OrderResource that extends JsonResource where i tried to used the $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)
      ];
 }

1条回答
手持菜刀,她持情操
2楼-- · 2019-08-29 01:14

Create subTotal accessor in Order Model

Order Model

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

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

   return $sub_total;
}

Now use it in OrderResource

public function 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)
  ];

}

Note: When you fetch Order then eager load Product

查看更多
登录 后发表回答