laravel - 集合资源中的“with”方法在另一个集合资源中调用不会返回
问题描述
我有这样的关系
用户可以有许多订单 ['user_id','id']。Order可以有很多OrderDetail。订单详情有一个产品
- 用户身份']
- 订单 ['user_id','id']
- OrderDetail ['order_id','product_id', 'quantity']。
现在我正在使用 Collection Resource 来获取所需的数据
$myOrder = new MyOrderCollection($this->order); //return
// MyOrderCollection.php
public function toArray($request)
{
return
[
'data' => $this->collection->transform(function($order)
{
return
[
'id'=> $order->id,
'orderDetails' => new MyOrderDetailCollection($order->orderDetails),
];
})
];
}
public function with($request)
{
return
[
'meta' =>
[
'amount' => $amount // return total of all the orders of that user
]
];
}
// MyOrderDetailCollection.php
public function toArray($request)
{
return
$this->collection->transform(function($singleOrder)
{
return
[
'id' => $singleOrder->id,
'quantity' => $singleOrder->quantity,
'total' => $total, // (quantity * price) return total price of single item of order
'product_details' => new ProductResource($singleOrder->product)
];
});
}
public function with($request)
{
return
[
'meta'=>
[
'grand_total_of_a_order' => $this->collection->sum('total')
]
];
}
//result
{
"data":
[
{
"id": 2,
"orderDetails":
[
{
"id": 2,
"quantity": 7,
"total": 140,
"product_details":
{
"price": 20
}
}
]
},
{
"id": 1,
"orderDetails":
[
{
"id": 1,
"quantity": 2,
"total": 20,
"product_details":
{
"price":10
}
},
{
"id": 1,
"quantity": 3,
"total": 90,
"product_details":
{
"price":30
}
}
]
}
],
"meta":
{
"amount":
{
"total" = 250 //calculated from another file
}
}
}
"meta": {
"amount": {
"grand_total_of_a_order" = xxx
}
}
不返回从“with”方法调用。我认为应该在给定响应中的 order_details 之后返回。
为什么以及如何解决?
解决方案
推荐阅读
- python-3.x - 从大字符串中提取子字符串
- mlflow - MLFlow UI 中的 INTERNAL_SERVER_ERROR
- python - 从多个文件中读取大数据并在python中聚合数据的最快方法是什么?
- node.js - 如何永久启动节点?增加节点内存大小
- configuration - 是否可以编辑或创建 apparmor 配置文件,并且不会丢失该软件的下一次更新时所做的更改?
- prometheus-alertmanager - 如何修改警报管理器的阈值
- reactjs - 如何在 Sun Editor 中使用预定义值将 React 状态值插入 HTML 模板?
- scala - 无法解决作为字符串传递的列的列名错误 - Spark Scala
- flutter - 使用 fromJson 中的灵活键进行初始化
- c# - MongoDB选择查询总是用C#返回null?