如何批量更新 Laravel 中的多对多相关表?

How to mass update many to many related tables in Laravel?

我正在从外部 API 获取数据,我想 insert 或使用 Laravel 将这些数据更新为具有多对多关系的两个 table 和MySQL.

Table结构

订单Table

|id (Auto Increment /Not related to API) | order_id (from API) | some other columns |

产品Table

|id (Auto Increment /Not related to API) | product_id (from API) | some other columns |

Orders_Products Table

|order_id (FK) | product_id (FK) | quantity (int) | some other columns |

这是来自 API 的响应的数据结构。

orders : [
    order_id : 1234568586,
    some_fields : abcd,
    products : [
         {
             product_id : 14578546,
             quantity : 10,
             some_fields
         },
         {
             product_id : 24578546,
             quantity : 5,
             some_fields
         }
    ]
]

我需要做什么

我想 insertupdateIfExist 所有这些订单(进入订单 Table)及其产品(进入产品 table)并将关系映射(进入 Orders_Product Table).

我的方法

foreach (orders as order) {
    //insert/update Order and keep its id

    foreach(order->products as product){
        //fetch Product Model if it product_id already exists
        //else make a new Product Model.

        //insert/update Product
        //add relationship
   }
}

我的问题

我的方法很管用。我可以insert/update将所有需要的数据存入数据库。 但是我很确定这是非常低效的,因为数据库被查询了很多次。所以如果有大约 1000 个订单,这段代码将需要很长时间才能执行。 如果您能提供一种有效的方法,我将不胜感激。

从 API 创建数据结构的临时表,然后执行 insert into orders select ... from orders_tmp ... on duplicate key update ... 的 laravel 版本(产品也是如此)。

参考:MariaDB insert / MySQL insert

根据您 table 中的产品数量,您可以将它们全部检索到一个数组中,并使用 ID 进行索引。

这将使您避免每次都请求多个数据库。

// $products = [
//     1 => $product1,
//     2 => $product2,
//     ...
//     ];
$products = getAllMyProductsIndexedById();
foreach ($orders as $order) {
    //insert/update Order and keep its id

    foreach($order->products as $product){
        //fetch Product Model if it product_id already exists
        if(array_key_exists(product->id, $products){
            $productEntity = $products[product->id];
        } else {
            //else make a new Product Model.
            // and add it to the array $products
        }

        //insert/update Product
        //add relationship
   }
}