You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于新需求更新并删除Guide Steps表中的冗余记录?

解决方案:食谱步骤的增改删完整逻辑

问题背景

需要实现食谱步骤的创建/更新已有步骤,同时删除当前不需要的冗余步骤,当前仅能通过循环updateOrInsert实现增改,尝试使用upsert但缺少必要的唯一约束。


1. 给表添加联合唯一约束

同一个食谱的步骤号必然唯一,recipe_id + step_number天然具备唯一性,先给表添加联合唯一索引,满足upsert的使用要求:

// 创建新迁移文件执行(推荐,避免修改已上线的迁移)
Schema::table('guide_steps', function (Blueprint $table) {
    $table->unique(['recipe_id', 'step_number']);
});

执行迁移命令生效:

php artisan migrate

2. 使用upsert批量完成增改操作

替代循环的updateOrInsert,用upsert更高效地实现「存在则更新,不存在则创建」:

GuideStep::upsert(
    $groupedSteps,
    ['recipe_id', 'step_number'], // 匹配唯一约束的字段
    ['step_text', 'step_image']   // 需要更新的字段
);

3. 删除冗余的步骤条目

删除当前食谱中,不在传入的$groupedSteps列表里的步骤:

// 提取传入的所有步骤号
$currentStepNumbers = collect($groupedSteps)->pluck('step_number')->toArray();

// 删除该食谱下未被包含的步骤
GuideStep::where('recipe_id', $recipeId)
    ->whereNotIn('step_number', $currentStepNumbers)
    ->delete();

内容的提问来源于stack exchange,提问作者dmytroshved

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:42:15