Laravel如何基于id_feed_mappings批量更新多行数据
替换删除重插为基于id_feed_mappings的更新逻辑
要实现这个需求,你需要将原逻辑拆分为更新已有记录、插入新记录两个核心操作(可选同步清理无效旧记录),具体步骤及代码实现如下:
核心逻辑拆分
- 区分记录类型:把
$projectFieldOptions里的数据分成两类——包含id_feed_mappings的已有记录(需更新)、无id_feed_mappings的新记录(需插入),同时收集所有待更新记录的ID用于后续可选清理。 - 批量更新已有记录:以
id_feed_mappings为唯一标识,更新对应字段的值。 - 批量插入新记录:将无标识的新记录插入表中。
- 可选:清理无效旧记录:如果需要保证
id_feed和id_project下的记录完全与传入数据同步,删除不在传入列表中的旧记录。
Laravel框架代码示例
假设你有对应feed_mappings表的FeedMapping模型:
use App\Models\FeedMapping; use Illuminate\Support\Facades\DB; // 1. 拆分数据 $updateList = []; $insertList = []; $existingMappingIds = []; foreach ($projectFieldOptions as $option) { if (isset($option['id_feed_mappings']) && $option['id_feed_mappings']) { $updateList[] = $option; $existingMappingIds[] = $option['id_feed_mappings']; } else { // 确保新记录关联对应feed和project $option['id_feed'] = $id_feed; $option['id_project'] = $id_project; $insertList[] = $option; } } // 开启事务保证操作原子性 DB::beginTransaction(); try { // 2. 更新已有记录 foreach ($updateList as $item) { FeedMapping::where('id_feed_mappings', $item['id_feed_mappings']) ->update([ 'field_name' => $item['field_name'], // 替换为你实际需要更新的字段 'updated_at' => now() ]); } // 3. 插入新记录 if (!empty($insertList)) { FeedMapping::insert($insertList); } // 4. 可选:清理不在传入列表的旧记录 if (!empty($existingMappingIds)) { FeedMapping::where('id_feed', $id_feed) ->where('id_project', $id_project) ->whereNotIn('id_feed_mappings', $existingMappingIds) ->delete(); } DB::commit(); } catch (\Exception $e) { DB::rollBack(); // 异常处理:记录日志或返回错误响应 report($e); return response()->json(['error' => '操作失败'], 500); }
原生PHP/PDO代码示例
如果不用框架,基于PDO实现的逻辑如下:
// 假设已初始化PDO连接$pdo $updateStmt = $pdo->prepare("UPDATE feed_mappings SET field_name = :field_name, updated_at = NOW() WHERE id_feed_mappings = :id"); $insertStmt = $pdo->prepare("INSERT INTO feed_mappings (id_feed, id_project, field_name, created_at, updated_at) VALUES (:id_feed, :id_project, :field_name, NOW(), NOW())"); try { $pdo->beginTransaction(); // 更新逻辑 foreach ($updateList as $item) { $updateStmt->execute([ ':field_name' => $item['field_name'], ':id' => $item['id_feed_mappings'] ]); } // 插入逻辑 foreach ($insertList as $item) { $insertStmt->execute([ ':id_feed' => $id_feed, ':id_project' => $id_project, ':field_name' => $item['field_name'] ]); } // 可选:清理旧记录 if (!empty($existingMappingIds)) { $placeholders = implode(',', array_fill(0, count($existingMappingIds), '?')); $deleteStmt = $pdo->prepare("DELETE FROM feed_mappings WHERE id_feed = ? AND id_project = ? AND id_feed_mappings NOT IN ($placeholders)"); $params = array_merge([$id_feed, $id_project], $existingMappingIds); $deleteStmt->execute($params); } $pdo->commit(); } catch (PDOException $e) { $pdo->rollBack(); error_log($e->getMessage()); die("操作失败"); }
内容的提问来源于stack exchange,提问作者Shibbir
相关产品推荐
相关产品推荐

