没有不值得去解决的问题,也没有不值得去学习的技术!

Resolving Unique Key Conflicts When Reinserting Records After Soft Deletes in Laravel 6

In Laravel 6, after applying soft deletes to a model, re-inserting a record causes a unique key conflict

1. In Laravel 6, after applying soft deletes to a model, re-inserting a record causes a unique key conflict. See Figure 1.

In Laravel 6, after applying soft deletes to a model, re-inserting a record causes a unique key conflict
Figure 1
Plaintext
PS E:\wwwroot\object> php artisan theme-store:theme:install E:\wwwroot\object\resources\views\brooklyn 971c4f4d-097b-4a84-a914-0ef00b6e69da blade --force
Delete theme
Install theme to data repository
Installation failed because: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '971c4f4d-097b-4a84-a914-0ef00b6e69da-apps/internal/back-top/app.' for key 'theme_asset2_theme_id_asset_key_unique' (SQL: insert into `theme_asset2` (`asset_key`, `theme_id`, `mime_type`, `created_at`, `content`, `schema`, `category`, `updated_at`) values (apps/internal/back-top/app.json, 971c4f4d-097b-4a84-a914-0ef00b6e69da, application/json, 2022-08-26 01:59:53, {
  "title": "Back to top",
  "description": "Adds a button to the page that returns to the top of the page, improving user experience."
}
, ?, unknown, 2022-08-26 01:59:53))

2. The reason is that after applying soft deletes, when you use the delete method on a model instance, the current date and time are written to the deleted_at field. At the same time, soft-deleted records are automatically excluded from query results.

PHP

ThemeAsset::where('theme_id', $themeId)->delete();

3. Because the record was not hard deleted, a unique key conflict occurs when writing a new record.

4. Query results automatically exclude soft-deleted records. Therefore, you need to use the withTrashed method to retrieve models including the soft-deleted ones. Then use the forceDelete method to permanently delete the soft-deleted models from the database.

PHP

ThemeAsset::withTrashed()->where('theme_id', $themeId)->forceDelete();

5. The record is successfully hard deleted, and re-inserting no longer throws an error. See Figure 2.

The record is successfully hard deleted, and re-inserting no longer throws an error
Figure 2

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系