R
R
romashka_sky2015-02-09 16:38:40
MySQL
romashka_sky, 2015-02-09 16:38:40

How to delete an entry with foreign keys in MySQL using Doctrine ORM?

Create a test table

DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;

SET FOREIGN_KEY_CHECKS = 0;

CREATE TABLE Item
(
  id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  lastSnapshot_id INT,
  FOREIGN KEY (lastSnapshot_id) REFERENCES Snapshot (id)
);
CREATE UNIQUE INDEX UNIQ_4B73F3E6D6703629 ON Item (lastSnapshot_id);

CREATE TABLE Snapshot
(
  id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
  item_id INT,
  FOREIGN KEY (item_id) REFERENCES Item (id) ON DELETE CASCADE
);
CREATE INDEX IDX_D27AA25CD6703629 ON Snapshot (item_id);

INSERT INTO Item(id, name) VALUES
  (1, 'item1'),
  (2, 'item2'),
  (3, 'item3'),
  (4, 'item4')
;

INSERT INTO Snapshot(id, item_id) VALUES
  (1, 1),
  (2, 1),
  (3, 1),
  (4, 2)
;

UPDATE Item SET Item.lastSnapshot_id = 3 WHERE Item.id = 1;
UPDATE Item SET Item.lastSnapshot_id = 4 WHERE Item.id = 2;

When trying to delete a line from an Item with id=1
DELETE FROM Item WHERE Item.id = 1
, an error occurs:
Cannot delete or update a parent row: a foreign key constraint fails (`test`.`Item`, CONSTRAINT `Item_ibfk_1` FOREIGN KEY (`lastSnapshot_id`) REFERENCES `Snapshot` (`id`))

As far as I understand, the error occurs due to FOREIGN KEY and ON DELETE = CASCADE referring to each other.
On pure SQL, you can delete it by first setting FOREIGN_KEY_CHECKS = 0, but I want to use Doctrine ORM.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Evgenievich, 2015-02-09
@romashka_sky

/* @ORM\JoinColumn(name="application_id", referencedColumnName="id", nullable=true, onDelete="SET NULL") */

Those. put /* onDelete="SET NULL" */
And don't forget to do doctrine:schema:update

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question