假设我有一个产品的 API 响应
{
data: [
{
id: 3,
name: "Test Product",
price: "158.21",
quantity: 4,
income: 569.56
},
{
id: 4,
name: "Test Product",
price: "58.21",
quantity: 3,
income: 157.17
},
]
}
Run Code Online (Sandbox Code Playgroud)
有没有办法像这样将产品的所有收入加起来?
{
data: [
{
id: 3,
name: "Test Product",
price: "158.21",
quantity: 4,
income: 569.56
},
{
id: 4,
name: "Test Product",
price: "58.21",
quantity: 3,
income: 157.17
},
],
total: 726.73
}
Run Code Online (Sandbox Code Playgroud)
这是我的课程OrderProductResource扩展JsonResource
public function toArray($request)
{
$quantity = 0;
$overAllTotal = 0;
foreach($this->orders as $order){
$quantity += $order->pivot->quantity;
}
$sub_total = round($this->price * $quantity,2);
$discount = round((10 / 100) * $sub_total, 2);
$totalIncome = round(($sub_total - $discount), 2);
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'quantity' => $quantity,
'income' => $totalIncome,
];
}
Run Code Online (Sandbox Code Playgroud)
我尝试with在 Laravel 中使用该方法,但 API 响应仍然相同。
这是我的控制器
public function index(){
$errorFound = false;
$error = ['error' => 'No Results Found'];
$products = Product::with('orders');
if (request()->has('q')) {
$keyword = '%'.request()->get('q').'%';
$builder = $products->where('name', 'like', $keyword);
$builder->count() ? $products = $builder : $errorFound = true;
}
return $errorFound === false ? OrderProductResourceCollection::collection($products->latest()->paginate()) : $error;
}
Run Code Online (Sandbox Code Playgroud)
您需要定义2访问者总数quantity和income在产品型号
public function getQuantityAttribute()
{
$quantity = 0;
foreach($this->orders as $order){
$quantity += $order->pivot->quantity;
}
return $quantity;
}
public function getIncomeAttribute()
{
$sub_total = $this->price * $this->quantity;
$discount = round((10 / 100) * $sub_total, 2);
return round(($sub_total - $discount), 2);
}
Run Code Online (Sandbox Code Playgroud)
OrderProductResource像这样改变班级
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'quantity' => $this->quantity,
'income' => $this->income,
];
}
Run Code Online (Sandbox Code Playgroud)
创建资源集合类OrderProductResourceCollection为OrderProductResource这样的
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class OrderProductResourceCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection,
'total' => $this->collection->sum('income')
];
}
}
Run Code Online (Sandbox Code Playgroud)
现在在控制器中像这样使用它
$products = Product::with('orders')->get();
return response()->json(new OrderProductResourceCollection($products));
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看资源收集文档https://laravel.com/docs/5.6/eloquent-resources#concept-overview
| 归档时间: |
|
| 查看次数: |
5669 次 |
| 最近记录: |