【问题标题】:Upsert Only inserts and does not update the existing fieldUpsert 仅插入而不更新现有字段
【发布时间】:2021-05-31 01:14:21
【问题描述】:

我正在尝试将出勤率添加到出勤表中,如果给定日期和学生 ID 的出勤率已经在表中,我需要更新出勤类型。

但是 upsert 只是插入并且永远不会更新。

SmStudentAttendance::upsert($studentRows, ['student_id', 'attendance_date'], ['attendance_type']);

【问题讨论】:

  • 请分享更多细节

标签: mysql database laravel eloquent query-builder


【解决方案1】:

为时已晚,但它对我有用。在迁移中试试这个:

$table->unique(['student_id', 'attendance_date']);

或者您可以在 phpmyadmin(或类似工具)中为列添加唯一约束

【讨论】:

  • 请在您的答案中添加一些解释,以便其他人可以从中学习
【解决方案2】:

upsert 的工作原理完全一样

on duplicate key update on MySQL

它需要一个唯一的约束冲突来更新而不是插入。

所以直接在数据库中检查你是否有这样的违规行为。

您还可以通过示例了解更多信息,例如 https://www.amitmerchant.com/insert-or-update-multiple-records-using-upsert-in-laravel8/

【讨论】:

  • 我给出了两列来识别,但它不起作用。
  • 正如我在回答中所写,您需要违反包含主键的唯一键,如果 student_id 是 neiterh,则您不能使用 upsert
猜你喜欢
  • 2017-10-28
  • 1970-01-01
  • 2017-01-16
  • 2021-06-02
  • 2013-02-23
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 2011-02-12
相关资源
最近更新 更多