Symfony2 - 使用多对多关系持久保存数据

时间:2014-10-26 22:10:39

标签: php mysql symfony doctrine many-to-many

我正在使用Symfony2,并且我使用这些实体创建了多对多关系:

<?php
/** @Entity **/
class User
{
    // ...

    /**
     * @ManyToMany(targetEntity="Group", inversedBy="users")
     * @JoinTable(name="users_groups")
     **/
    private $groups;

    public function __construct() {
        $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

/** @Entity **/
class Group
{
    // ...
    /**
     * @ManyToMany(targetEntity="User", mappedBy="groups")
     **/
    private $users;

    public function __construct() {
        $this->users = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

如果我更新我的数据库,我会得到这个MySQL架构:

CREATE TABLE User (
    id INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;
CREATE TABLE users_groups (
    user_id INT NOT NULL,
    group_id INT NOT NULL,
    PRIMARY KEY(user_id, group_id)
) ENGINE = InnoDB;
CREATE TABLE Group (
    id INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;
ALTER TABLE users_groups ADD FOREIGN KEY (user_id) REFERENCES User(id);
ALTER TABLE users_groups ADD FOREIGN KEY (group_id) REFERENCES Group(id);

我需要知道如何将一对夫妇插入名为'users_groups'的关系表中,以表达用户与群组之间的关联。

当我想将数据插入数据库时​​,我通常会尝试使用与数据库表关联的实体来保留这些数据,但在这种情况下我无法访问此实体,因为表'users_groups'是由关系,没有实体类。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

好的,所以从关系模型转向对象模型在开始时可能有点压倒性。

正如您所注意到的,您无法访问中间表,只能访问它的终端。请注意User构造函数:

public function __construct() {
    $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
}

它创建了关系另一侧的对象的集合(基本上是列表)。这是管理中间表的方法 - 通过将对象插入集合中。

试着考虑一下。 N:M关系(你正试图实现)实际上只是一组User个,其中每个都包含Group的列表。

所以,不用多说,这就是你应该做的事情:

$em = ... // instance of entity manager

$user = new User();

$g1 = new Group();
$g2 = new Group();

$user->getGroups()->add($g1);
$user->getGroups()->add($g2);

$em->persist($g1);
$em->persist($g2);
$em->persist($user);

$em->flush();

关于这个主题有很多细节,但我认为你应该能够在这里开始使用。希望它有所帮助...

相关问题