【发布时间】:2018-08-09 14:18:40
【问题描述】:
假设我有一个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)
];
}
【问题讨论】:
-
你想在哪里访问它?
-
在我的订单中,或者其他解决方案是在订单模型上制作访问器?
-
是的,在订单模型中创建访问器。您可以使用
$product->income访问它,但在当前情况下不会给您正确的结果