【问题标题】:Laravel eager loading use parents column valueLaravel 急切加载使用父列值
【发布时间】: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你们能给我一些提示,让它加载得更快吗?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    你可以尝试分块数据

    Product::with('racks')->chunk(100, function ($products) use($results) {
        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)
                ]);
            }
        }
    });
    

    当你对数据进行分块时,你一次只能获取 x 数量的项目。在您的情况下,一次 100 个项目。

    https://laravel.com/docs/8.x/queries#chunking-results

    【讨论】:

      猜你喜欢
      • 2014-08-13
      • 2021-04-23
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2013-05-16
      • 2020-01-13
      • 1970-01-01
      相关资源
      最近更新 更多