I am getting a foreign key constraint sql error when trying to add an entry through a front end form.

<form method="post" accept-charset="UTF-8">
  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="entries/saveEntry">
  <input type="hidden" name="entryId" value="{{ entry.id }}">
  <select name="fields[vendor][]">
    {% for v in craft.entries.section('vendors') %}
      <option value="v.id">{{v.title}}</option>
    {% endfor %}
  <input type="submit" value="Submit"/>

vendor is an Entries fieldtype, for unlimited entries from the vendors channel. Very similar code for adding a category works fine.

The error (complete with back-ticks):

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (metro.craft_relations, CONSTRAINT craft_relations_targetId_fk FOREIGN KEY (targetId) REFERENCES craft_elements (id) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO craft_relations (fieldId, sourceId, sourceLocale, targetId, sortOrder, dateCreated, dateUpdated, uid) VALUES (:row0_col0, :row0_col1, NULL, :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7). Bound with :row0_col0='13', :row0_col1='39', :row0_col3='v.id', :row0_col4=1, :row0_col5='2016-02-13 08:28:03', :row0_col6='2016-02-13 08:28:03', :row0_col7='e455a06e-8f9d-4299-ad57-93577907f9a0'

  • Can you share the actual FK constraint error?
    – Brad Bell
    Commented Feb 13, 2016 at 3:33
  • @BradBell added Commented Feb 13, 2016 at 8:30
  • Are there any other fields in the vendors channel? Also, could you enable devMode and share the stack trace leading up to the error?
    – Brad Bell
    Commented Feb 15, 2016 at 0:08
  • @BradBell Filed a support ticket, since you are implying this is a bug. Commented Feb 15, 2016 at 3:33
  • since you are implying this is a bug. - well, just trying to figure out what's going on. :) I think I see though so adding an answer.
    – Brad Bell
    Commented Feb 16, 2016 at 3:01

1 Answer 1


I think the problem is this:

<option value="v.id">{{v.title}}</option>

Try changing it to:

<option value="{{ v.id }}">{{v.title}}</option>
  • aarg! Hope this will help someone else with a 'foreign key constraint' sql error. Commented Feb 16, 2016 at 3:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.