0

I have entity "A" with the following property:

manyToOne:
    b:
        targetEntity: App\Entity\B
        joinColumn:
            name: b_id
            referencedColumnName: id

How can I update the value of entity "A", when delete the entity "B", instantly?

e.g.:

$a = new A();
$b = $bRepository->find(1);
$a->setB($b);
$em->persist($a);
$em->flush();

// table a:         table b:
// +----+------+    +----+
// | id | b_id |    | id |
// +----+------+    +----+
// |  1 |    1 |    |  1 |
// +----+------+    +----+

$em->remove($b);
$em->flush();

// table a:         table b:
// +----+------+    +----+
// | id | b_id |    | id |
// +----+------+    +----+
// |  1 | NULL |
// +----+------+

I can do it with the MySQL trigger, but maybe there exists some configuration for table or doctrine to do it w\o triggers?

The main problem is that I can't modify the entity "B" or update entity "A" with $a->setB(null); $em->persist($a); on "B" removing, because it in shared bundle and using in several projects

Serghei Niculaev
  • 513
  • 7
  • 17
  • Possible duplicate of [Doctrine 2 OneToMany Cascade SET NULL](https://stackoverflow.com/questions/8858645/doctrine-2-onetomany-cascade-set-null) – Serghei Niculaev Jun 16 '19 at 23:40

1 Answers1

0

Found the solution I didn't noticed before: MySQL "ON DELETE" referential action with value "SET NULL". See the fiddle: http://sqlfiddle.com/#!9/49e79b/1

ALTER TABLE a ADD FOREIGN KEY (b_id) REFERENCES b (id) ON DELETE SET NULL ON UPDATE CASCADE;
manyToOne:
    b:
        targetEntity: App\Entity\B
        joinColumn:
            name: b_id
            referencedColumnName: id
            onDelete: SET NULL
Serghei Niculaev
  • 513
  • 7
  • 17