update entity parse batch insert

This commit is contained in:
2025-12-12 11:12:52 +08:00
parent b8e3b12316
commit c726020c8c
3 changed files with 172 additions and 32 deletions
+18 -7
View File
@@ -102,15 +102,26 @@ class OrderConsumer extends ConsumerMessage
// message 中包含 raw dataraw data (数组或集合 -> 优先为集合类型 ) 则需要通过 entityMap 方法转换为 ORM 对象。
$entityMapResult = $parse->entityMap($data['raw_data'] ?? []);
// $entityMapResult 应该是一个内部元素为 Model 的集合
// 将 LazyCollection 转为数组,准备批量操作
$dataToUpsert = $entityMapResult->all();
if (empty($dataToUpsert)) {
dump('No data to process');
return Result::ACK;
}
dump("Processing " . count($dataToUpsert) . " order(s) with batch upsert");
Db::beginTransaction();
// 假设 $entityMapResult 为集合 @Collection 对象
$entityMapResult->each(function ($el) use ($entity) {
$clone = clone $entity;
$clone->fill($el);
$clone->save();
});
// 使用 upsert 批量处理插入和更新
// 利用数据库唯一索引自动判断是插入还是更新
// 解决了重复订单推送的问题:存在则更新,不存在则插入
$entity->newQuery()->upsert(
$dataToUpsert,
$parse->getUniqueBy(), // 从解析器获取唯一键字段
$parse->getUpdateFields() // 从解析器获取可更新字段
);
Db::commit();