如何截断 MySQL 中使用 ManyToMany 字段的 table

How truncate a table in MySQL that is using ManyToMany field

我在 MySQL 中有一个 table,它有一个 ManyToMany 字段,我想截断 table,但是当我尝试它时,我收到以下错误:

ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint ...

我正在将 Symfony 与 Doctrine 一起使用,但如果可能的话,我有兴趣了解如何通过控制台进行操作

class Project {

  /**
  * @ORM\ManyToMany(targetEntity="Shipping", mappedBy="projects")
  **/
  private $employee;
}

class Employee{

  /**
  * @ORM\ManyToMany(targetEntity="Product", inversedBy="employee")
  * @ORM\JoinTable(name="middle_table")
  **/
  protected $projects;
}

外键意味着您有两个 table 并且每个更新都必须与外键约束引用的 table 兼容。

可能的解决方案在这里:How do I truncate tables properly?

SET FOREIGN_KEY_CHECKS = 0; -- Disable foreign key checking.
TRUNCATE TABLE forums;
TRUNCATE TABLE dates;
TRUNCATE TABLE remarks;
SET FOREIGN_KEY_CHECKS = 1; -- Enable foreign key checking.

现在您在 middle_table 中的外键不允许您从项目 table 中删除记录。换句话说,您在 middle_table 中有一个 link 到 Project,它没有机会从 Project 中删除行。因此,您应该更改外键的定义以允许删除,您可以将 link 设置为 null 或进行级联删除。我更喜欢第二个选项,所以将注释更改为以下,它应该允许您删除项目 table 中的行,它还会删除 link 到 middle_table 中的项目。

class Project {

  /**
  * @ORM\ManyToMany(targetEntity="Shipping", mappedBy="projects", cascade={"remove"})
  **/
  private $employee;
}

文档:
Doctrine association mapping
mysql foreign key contraint