SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '17-1' for key 'elements_sites.idx_yuhsxkwkfvwtibgopgvkaghhoafftioctgde'
The SQL being executed was: INSERT INTO `elements_sites` (`elementId`, `siteId`, `title`, `slug`, `uri`, `enabled`, `content`, `dateCreated`, `dateUpdated`, `uid`) VALUES (17, 1, 'Entry #17', 'foo', 'blog/foo', 1, NULL, '2024-08-10 20:12:30', '2024-08-10 20:12:30', '8db0279e-b40a-4727-b352-cf5db88f64f4')
This only happens when trying to save something outside of the normal CP entry form, so it may have something to do with saving directly to a live element vs starting as a draft. Craft 4 has no problem with the same code.
What happened?
Description
If you need to (re)-save an element in its
afterSave, you will get an integrity constraint violation on theelements_sitestable, unless you manually includeisNewForSite = false.This only happens when trying to save something outside of the normal CP entry form, so it may have something to do with saving directly to a live element vs starting as a draft. Craft 4 has no problem with the same code.
Here's a gist of a contrived example where you want to put the entry ID in the title, so you re-save the entry in the
afterSaveevent: https://gist.github.com/timkelty/1cfb09a9611587552ed0f81ab99b1af7Craft CMS version
5.3
Related Issues
https://github.com/craftcms/craftnet/pull/1098