使用条令2删除Zend中多对多实体的记录


Delete record from many to many entity in Zend using Doctrine 2

我正在研究Zend学说。我有一个多对多实体groups_contacts,它具有链接到相关表groupcontact并在group实体中创建的字段group_idcontact_id

我在group实体中创建groups_contacts,这是一种多对多关系。

以下是删除操作的代码:

public function deleteGroupMemberAction() {
    $auth_service = $this->getServiceLocator()->get('doctrine.authenticationservice.orm_default');
    $objectManager = $this->getServiceLocator()->get('Doctrine'ORM'EntityManager');
    $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
    $user = $auth_service->getIdentity();
    //die($_POST['g_id'] . ' removed');
    $query_deleteMember = $em->createQuery('delete from groups_contacts gc where gc.contact_id = 7 and gc.group_id = 1');
    $numDeleted = $query_deleteMember->execute();
    die($query_deleteMember. ' removed');
    $objectManager->flush();
    die($title . ' removed');
}

此函数调用了ajax调用,该调用运行良好。

我不知道为什么删除查询不起作用,我尝试了其他方法,但得到了相同的结果。有人有什么想法吗?

您必须指定到实体的映射

delete from MyMapping:groups_contacts gc where gc.contact_id = 7 and gc.group_id = 1

或者放上你的命名空间:

delete from Your'Name'Space'groups_contacts gc where gc.contact_id = 7 and gc.group_id = 1

但这还不够,因为您不能直接访问这些contact_idgroup_id列。所以你必须写:

delete from MyMapping:groups_contacts gc JOIN gc.contact c JOIN gc.group g where c.id = 7 and g.id = 1

哇两个加入。。这在本机SQL中应该更简单。它甚至执行那些JOIN吗?也许Doctrine会对其进行优化,而不会在最终查询中使用JOIN。

这个用例有点奇怪。假设你有一个网站,上面列出了群组及其联系人。关系由groups_contacts表示(在网站说明中,只有当关系需要保存数据时,才应将其作为一个单独的实体)。然后,当用户想要删除一个关系(断开联系人与群组的连接)时,该关系(由groups_contacts表示)可以用它自己的id来识别。然后,您的查询将变为:

DELETE FROM MyMapping:groups_contacts gc WHERE gc.id = <user clicked relation>

这是的解决方案

控制器

$group=$em->find("Application''Entity''group",$group_id);

        if ($group->getCreatedBy()->getId() == $user->getId()) {
            $contact = $em->find("Application'Entity'UserProfile", $contact_id);
            if (isset($contact)) {
                $group->getContacts()->removeElement($contact);
                $objectManager->persist($group);
                $objectManager->flush();

}

集团实体

/**
 *
 * @ORM'ManyToMany(targetEntity="UserProfile")
 * @ORM'JoinTable(name="groups_contacts",
 *      joinColumns={@ORM'JoinColumn(name="group_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM'JoinColumn(name="contact_id", referencedColumnName="id")}
 *      )
 */

私人$联系人

最好以这种方式处理多对多关系,在这种关系中,您必须使用removeElement从关联实体中获取要删除的组和联系人id,然后使用组的相关id进行持久化