laravel api资源添加其他数据

标签 laravel laravel-5

假设我有产品的 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/

相关文章:

laravel - 尝试catch在Laravel中间件中无法正常工作吗?

php - 当密码错误时动态增加PBKDF2的迭代次数

php - 无法从大型表行中检索记录

php - Laravel 4/5 搜索表单,如

jquery - 如何在数据表中添加if语句?

php - Laravel Blade : syntax error, 意外 'endif' (T_ENDIF)

php - Laravel 调用未定义的方法 Illuminate\Html\HtmlServiceProvider::style()`

javascript - HTML 表单未在 Safari 和 iOS Safari 上提交

php - 带有 FFMPEG 的 Laravel Process() 对任何甚至很大的视频都会超时

php - Laravel 事件 : updating vs updated?