{"record":{"id":"caa8bb582a7b6e18","repo":"medusajs/medusa","slug":"23503","errorCode":"23503","errorMessage":"You tried to set relationship ${info?.keys.map((key, i) => `${key}: ${info.values[i]}`)}, but such entity does not exist","messagePattern":"You tried to set relationship (.+?): (.+?)`\\)\\}, but such entity does not exist","errorType":"validation","errorClass":"MedusaError","httpStatus":404,"severity":"error","filePath":"packages/core/utils/src/dal/mikro-orm/db-error-mapper.ts","lineNumber":71,"sourceCode":"  }\n\n  if (\n    err instanceof InvalidFieldNameException ||\n    (err as any).code === \"42703\"\n  ) {\n    const userFriendlyMessage = err.message.match(/(column.*)/)?.[0]\n    throw new MedusaError(\n      MedusaError.Types.INVALID_DATA,\n      userFriendlyMessage ?? err.message\n    )\n  }\n\n  if (\n    err instanceof ForeignKeyConstraintViolationException ||\n    (err as any).code === \"23503\"\n  ) {\n    const info = getConstraintInfo(err)\n    throw new MedusaError(\n      MedusaError.Types.NOT_FOUND,\n      `You tried to set relationship ${info?.keys.map(\n        (key, i) => `${key}: ${info.values[i]}`\n      )}, but such entity does not exist`\n    )\n  }\n\n  throw err\n}\n\nconst getConstraintInfo = (err: any) => {\n  const detail = err.detail as string\n  if (!detail) {\n    return null\n  }\n\n  const [keys, values] = detail.match(/\\([^\\(]*\\)/g) || []\n","sourceCodeStart":53,"sourceCodeEnd":89,"githubUrl":"https://github.com/medusajs/medusa/blob/5e06e544a296b9033f20f71f11c559f81a0e5739/packages/core/utils/src/dal/mikro-orm/db-error-mapper.ts#L53-L89","documentation":"PostgreSQL error 23503 (foreign_key_violation) was caught by Medusa's dbErrorMapper and re-thrown as a MedusaError of type NOT_FOUND. It occurs when an INSERT/UPDATE sets a foreign key column to a value that has no matching row in the related table — i.e. you tried to link entity A to entity B whose ID does not exist. The message lists the offending key/value pairs extracted from the constraint info.","triggerScenarios":"Creating or updating a record with a relation ID that doesn't exist: e.g. creating a cart with customer_id: 'cus_x' after that customer was deleted, updating an order's sales_channel_id to a removed channel, or upserting a product with category_ids containing stale IDs.","commonSituations":"Hard-deleting a related record while other rows still reference it (soft-deleted modules vs raw SQL deletes); using fixture/seed IDs that no longer exist across environments; passing an empty-string or undefined-coerced ID into a relation field; race where the related entity is deleted between read and write.","solutions":["Check that every relation ID you are setting actually exists before the write (query the related service by ID first, or validate incoming IDs).","If the related record was deleted intentionally, clear/null the relation on referencing records first, or stop referencing it in your payload.","If you must delete the related record, use the module's soft-delete or cascade rules instead of raw SQL deletes that bypass FK cleanup.","Re-seed or fix stale fixture/export IDs when promoting data between environments."],"exampleFix":"// before\nawait orderService.updateOrders([{ id: orderId, sales_channel_id: \"sc_dead\" }])\n\n// after\nconst sc = await salesChannelService.retrieveSalesChannel(\"sc_dead\") // throws NOT_FOUND early if missing\nawait orderService.updateOrders([{ id: orderId, sales_channel_id: sc.id }])","handlingStrategy":"validation","validationCode":"const ids = [payload.customer_id, payload.sales_channel_id].filter(Boolean)\nconst existing = await someService.list({ id: ids })\nif (existing.length !== new Set(ids).size) {\n  throw new MedusaError(MedusaError.Types.NOT_FOUND, \"Referenced entity does not exist\")\n}","typeGuard":null,"tryCatchPattern":"try {\n  await service.create(payload)\n} catch (err) {\n  if (err instanceof MedusaError && err.type === MedusaError.Types.NOT_FOUND && /such entity does not exist/.test(err.message)) {\n    // parse key/value pairs, validate or clear the relation, then retry\n  }\n  throw err\n}","preventionTips":["Validate all incoming relation IDs against their services before writing.","Avoid raw SQL hard-deletes of entities referenced by foreign keys; use module soft-deletes.","Log the offending key/value pairs from the message when it fires to pinpoint the payload field."],"tags":["database","postgres","foreign-key","relation","not-found"],"backgroundTag":"foreign-key-constraint-violation","analyzedSha":"5e06e544a296b9033f20f71f11c559f81a0e5739","analyzedAt":"2026-08-27T07:24:39.599Z","schemaVersion":2},"datasetVersion":"2026-08-27T08:17:20.692Z"}