mysql - 如何使用 Doctrine 更新另一个表中删除行的表行?

标签 mysql doctrine-orm

我的实体“A”具有以下属性:

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

当删除实体“B”时,如何立即更新实体“A”的值?

例如:

$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 |
// +----+------+

我可以使用 MySQL 触发器来完成此操作,但也许存在一些表或学说的配置来无需触发器来完成此操作?

主要问题是我无法使用 $a->setB(null); 修改实体“B”或更新实体“A”; $em->persist($a); 删除“B”,因为它在共享包中并在多个项目中使用

最佳答案

找到了我之前没有注意到的解决方案:MySQL "ON DELETE" referential action值为“SET NULL”。请参阅 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

关于mysql - 如何使用 Doctrine 更新另一个表中删除行的表行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56493485/

相关文章:

php - 在 Doctrine 2 中指定表类型/存储引擎

php - 主键和外键同时与学说 2

Mysql查询两个外键到一个主键

MySql 数据库到 Microsoft Server Management Studio

php - 为什么实体 getter 返回 null 而不是 0?

php - Doctrine2 加入 SUM

php - Doctrine multiple OneToMany/ManyToOne 双向完整性约束违反

mysql - 电影数据库的 SQL 查询

php - 与fuelphp orm的复合键关系

php - MySql关系型数据库困惑