gpt4 book ai didi

laravel api资源添加其他数据

转载 作者:行者123 更新时间:2023-12-02 21:05:45 26 4
gpt4 key购买 nike

假设我有产品的 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
},
]
}

有没有一种方法可以像这样将产品的所有收入相加?

{
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
}

这是我的类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,
];
}

我尝试在 Laravel 中使用 with 方法,但 API 响应仍然相同。

这是我的 Controller

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

最佳答案

您需要定义 2 Accessor产品模型中的总数量收入

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

像这样更改OrderProductResource

public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'quantity' => $this->quantity,
'income' => $this->income,
];
}

OrderProductResource创建一个资源集合类OrderProductResourceCollection,如下所示

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')
];
}
}

现在在 Controller 中像这样使用它

$products = Product::with('orders')->get();
return response()->json(new OrderProductResourceCollection($products));

您可以在这里查看资源采集文档https://laravel.com/docs/5.6/eloquent-resources#concept-overview

关于laravel api资源添加其他数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51742584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com