77

The error

Cannot delete or update a parent row: a foreign key constraint fails.

The classes

class Teacher {

    /**
     *@ORM\OneToMany(targetEntity="publication", mappedBy="teacher")
     */
    protected $publications;
}

class Publication {

    /**
     * @ORM\ManyToOne(targetEntity="Teacher", inversedBy="publications")
     * @ORM\JoinColumn(name="teacher_id", referencedColumnName="id")
     */
    protected $teacher;
}

I want

What I want is to make it that when you delete a teacher, the id_teacher is modified to NULL. I want to keep the publication but without reference to Professor.

I don't know how do that in Doctrine, Is it possible? Or always the relationship has to be with a teacher?

Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202
Nicolas Lino
  • 771
  • 1
  • 5
  • 4

2 Answers2

208

You should add the option onDelete="SET NULL" in the annotation of your entity Publication like this:

class Publication
{
    /**
    * @ORM\ManyToOne(targetEntity="Teacher", inversedBy="publications")
    * @ORM\JoinColumn(name="teacher_id", referencedColumnName="id", onDelete="SET NULL")
    */
    protected $teacher;
}

This modification is registered in the table declaration itself. Hence, you need a database migration or a schema change for this to take effect.

starball
  • 20,030
  • 7
  • 43
  • 238
David Barreto
  • 8,887
  • 7
  • 32
  • 46
  • 36
    Please note that you have to update your database schema after you've added this. – priktop Feb 10 '15 at 10:58
  • 17
    * @ORM\JoinColumn(onDelete="SET NULL") is enough – Vasilii Suricov Jan 11 '20 at 13:47
  • 6
    This solution acts directly on the database and not on doctrine, which is fine but be careful if you use mechanisms like [soft-deleteable](https://github.com/Atlantic18/DoctrineExtensions/blob/v2.4.x/doc/softdeleteable.md). If your entity is being soft-deleted, it won't trigger SET_NULL and your child entity will point to a "deleted" object. You'll need to add a doctrine listener to make it work (depending on the behaviour you want). – bachinblack Aug 19 '20 at 14:30
7

For Symfony 6 (PHP 8)

#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
Gigoland
  • 1,287
  • 13
  • 10
  • Thank you, and for beginners, remember to run the following command after this change : `php bin/console doctrine:schema:update --force` – LinkmanXBP Nov 24 '22 at 15:48