【问题标题】:laravel api resource add other datalaravel api 资源添加其他数据
【发布时间】:2018-08-08 08:59:21
【问题描述】:

假设我有一个产品的 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 响应仍然相同。

这是我的控制器

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

【问题讨论】:

  • 您使用的是哪个变压器?分形?

标签: laravel laravel-5


【解决方案1】:

您需要在 Product Model 中定义 2 个Accessor 来表示 quantityincome 的总数

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

现在在控制器中像这样使用它

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

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

【讨论】:

  • 方法 Illuminate\Database\Query\Builder::mapInto 不存在。
  • return $errorFound === false ? response()->json(OrderProductResourceCollection::collection($products->latest()->paginate())) : $error;
  • 但是当我在扩展 JsonResource 的典型资源类上尝试它时,它工作正常
  • 还是一样的先生
【解决方案2】:

试试这个:

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,

        //your relation
        'realtion_name' => $this->relation_name
    ];
}

【讨论】:

  • 当我把它放的时候它会重复
猜你喜欢
  • 1970-01-01
  • 2010-11-09
  • 2020-05-09
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-02-01
  • 2018-02-26
相关资源
最近更新 更多