【问题标题】:symfony2 deleteForm not working finesymfony2 deleteForm 无法正常工作
【发布时间】:2016-04-06 13:00:06
【问题描述】:

我有 2 个实体。我想删除服务行。

我试过了:

$em = $this->getDoctrine()->getEntityManager();

$service = $em->getRepository('AppBundle:Service')->find(1);

$em->移除($service);

$em->flush();

通过这种方式,它删除了所有包含此类别 ID 的行。对不起我的英语不好。让我用另一种方式解释你:

           BEFORE                     AFTER delete id 1 from service
+----+------+  +----+------+-----+  +----+------+  +----+------+-----+
+ id + ca_  +  + id + se_  + ca_ +  + id + ca_  +  + id + se_  + ca_ +
+    + name +  +    + name + id  +  +    + name +  +    + name + id  +
+----+------+  +----+------+-----+  +----+------+  +----+------+-----+
+ 1  + A    +  + 1  + A1   + 1   +  +    +      +  +    +      +     +
+----+------+  +----+------+-----+  +----+------+  +----+------+-----+
+ 2  + B    +  + 2  + A2   + 1   +  + 2  + B    +  +    +      +     +
+----+------+  +----+------+-----+  +----+------+  +----+------+-----+
+ 3  + C    +  + 3  + B1   + 2   +  + 3  + C    +  + 3  + B1   + 2   +
+----+------+  +----+------+-----+  +----+------+  +----+------+-----+

我该如何解决?

服务实体:

/**
* Service
*
* @ORM\Table(name="service")
* @ORM\Entity(repositoryClass="AppBundle\Repository\ServiceRepository")
*/
class Service {
 ...

 /**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="services", cascade={"persist","remove"})
 * @ORM\JoinColumn(onDelete="CASCADE")
 */
 private $caId;

 /**
 * Set caId
 *
 * @param \AppBundle\Entity\Category $caId
 *
 * @return Service
 */
 public function setCaId(\AppBundle\Entity\Category $caId = null)
 {
     $this->caId = $caId;
     return $this;
 }

 /**
 * Get caId
 *
 * @return \AppBundle\Entity\Category
 */
 public function getCaId()
 {
     return $this->caId;
 }
}

类别实体:

/**
* Category
*
* @ORM\Table(name="category")
* @ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
*/
class Category {
 ...

 /**
 * @ORM\OneToMany(
 *   targetEntity="Service",
 *   mappedBy="caId"
 * )
 */
 private $services;

 /**
 * Constructor
 */
 public function __construct()
 {
   $this->services = new ArrayCollection();
 }

 /**
 * Get orders
 *
 * @return Collection
 */
 public function getServices()
 {
   return $this->services;
 }
}

【问题讨论】:

  • 哪个类别被分配给已删除的服务?而第二个服务实体被删除到?它属于哪个类别?
  • 我刚刚更新了我的表格。请检查一下。第二个服务被删除到。
  • 可能是ID实体映射错误

标签: symfony one-to-many sql-delete delete-row many-to-one


【解决方案1】:

我发现您的映射配置方式存在两个问题:

  1. 在您的 Service 实体中,您已配置为级联删除操作。这意味着当Service 对象被删除时,与之关联的Category 实体也将被删除。

  2. 映射中的第二个关键部分是@ORM\JoinColumn(onDelete="CASCADE")。在数据库级别,这会导致当 category 表中的条目被删除(因为 1 而发生)时,service 表中引用已删除类别的每条记录都将被删除(这就是为什么第二个服务丢失)。

通过查看您的模型,我假设将您的 Service 实体中的 cascade={"persist", "remove"} 更改为仅 cascade={"persist"} 就足够了(也许您甚至不需要级联持久化操作)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 2013-05-22
    • 2015-01-29
    • 1970-01-01
    • 2016-09-01
    • 2012-07-11
    • 2018-04-08
    相关资源
    最近更新 更多