且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除多对多表中的记录

更新时间:2022-11-27 21:21:39

Doctrine将数据视为对象而不是表行。因此,在Doctrine术语中,存在组对象(其中包含组的用户等),并且存在用户对象(每个对象具有存储用户所在的组的属性)。但是没有UserGroup对象。 Doctrine(和任何ORM系统)的想法是让开发人员忘记数据库可能需要的这些中间表,但是在程序的对象模型方面不是必需的。

Doctrine thinks about the data as objects, rather than as table rows. So, in Doctrine terms, there are Group objects (which hold the Group's users, among other things) and there are User objects (each one of which has a property storing the Groups that the user is in). But there are no UserGroup objects. The idea of Doctrine (and any ORM system) is to let the developer forget about these intermediate tables that the database might need but that aren't necessary in terms of the program's object model.

所以你想做的是加载相关的User对象,从它的$ groups属性中删除该组,并保留修改后的User对象。 (或反之亦然,即加载相关的Group对象,并从中删除用户。)DQL可能可以处理这一点,但是我认为没有DQL会更容易,因为DQL的DELETE语句用于删除整个对象,而不是修改他们的属性。

So what you want to do is load up the relevant User object, remove the group from it's $groups property, and persist the modified User object. (Or vice-versa, i.e. load up the relevant Group object and remove the User from it.) DQL might be able to handle this, but I think it's easier to do it without DQL as DQL's DELETE statement is for deleting whole objects, not modifying their properties.

尝试:

$user = $em->find('User', $userId);
$user->removeGroup($groupId); //make sure the removeGroup method is defined in your User model. 
$em->persist($user);
$em->flush(); //only call this after you've made all your data modifications

注意:如果您不在您的用户模型中有一个removeGroup()方法(我认为Symfony可以为您生成一个,但是我可能会出错),该方法可能如下所示。

Note: if you don't have a removeGroup() method in your User model (I think Symfony can generate one for you, but I could be wrong), the method could look as follows.

//In User.php, and assuming the User's groups are stored in $this->groups, 
//and $groups is initialized to an empty ArrayCollection in the User class's constructor
//(which Symfony should do by default).

class User
{
    //all your other methods

    public function removeGroup($group)
    {
        //optionally add a check here to see that $group exists before removing it.
        return $this->groups->removeElement($group);
    }
}