Problem/Motivation
SQL exception thrown when creating translation of node with paragraph containing media reference field.
Steps to reproduce
Create a paragraph type with text and media reference fields.
Make this paragraph type translatable.
Create a node with this paragraph type.
Try to add translation to another language.
Exception is thrown
SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "media_usage__media_reference__key"
DETAIL: Key (mid, entity_type, bundle_name, eid, langcode, submodule)=(437, node, page, 925, de, meu_paragraphs) already exists.: INSERT INTO "media_usage" ("mid", "entity_type", "bundle_name", "eid", "langcode", "submodule") VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5); Array
(
)
In this case "de" is source language.
It appears that $parent->language()->getId()
returns source language because at this point parent node translation is not saved into database yet. So $parent = $entity->getParentEntity();
returns original node.
Proposed resolution
Use language of paragraph entity instead.