假设我的accessor
模型有一个Product
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)
];
}
答案 0 :(得分:1)
在订单模型中创建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