【发布时间】:2023-03-20 22:00:02
【问题描述】:
这是我的场景,我有 2 个表 Product 和 Rack。它们有多对多的关系,所以有一个数据透视表(HistoryClass)来连接它们。
表格
这是我们的产品表:
| id | Name |
|---|---|
| 1 | Product A |
| 2 | Product B |
| 3 | Product C |
机架桌:
| id | code |
|---|---|
| 1 | X1 |
| 2 | Y2 |
| 3 | Z3 |
历史表:
| product_id | rack_id | historyable_id | historyable_type | quantity |
|---|---|---|---|---|
| Product A | X1 | 1 | Receive | 10 |
| Product A | Y1 | 1 | Receive | 5 |
| Product A | X1 | 1 | Delivery | 2 |
| Product B | X1 | 2 | Receive | 10 |
我想得到这样的列表:
| product_id | rack_id | historyable_id | historyable_type | quantity |
|---|---|---|---|---|
| Product A | X1 | 1 | Receive | 8 |
| Product A | Y1 | 1 | Receive | 5 |
| Product B | X1 | 2 | Receive | 10 |
如果类型 receive 是“借方”并且 delivery 是“贷方”来计算数量,我在这里有两个唯一列 product_id 和 rack_id。
这是我现在的方法:
public function collection()
{
$products = Product::with('racks')->get();
$results = collect();
foreach ($products as $product) {
foreach ($product->racks as $rack) {
$rackWithHistory = $rack->load(['history' => function ($q) use ($product) {
return $q->where('product_id', $product->id)->with('histories:id');
}]);
$results->push([
'product_name' => $product->name,
'product_description' => $product->description,
'location' => $rack->code,
'quantity' => $rack->getQuantity($rackWithHistory->history)
]);
}
}
return $result;
}
它有效,但在需要很长时间的大数据(尝试 2000 行)中,并且总是接触
php - Allowed memory size of 134217728 bytes exhausted你们能给我一些提示,让它加载得更快吗?
【问题讨论】: