我正在尝试使用 MongoDB 中的关系,使用 Symfony2 和 DoctrineMongoDBBundle 根据Doctrine MongoDB Object Document Mapper 演示文稿$User->setOrganization($Organization)
的幻灯片 49,分配,以$Organization::users[0]
引用用户对象就足够了。在文档中说我必须使用 inversedBy 和 mappedBy 选项。我有类似的方案(用户属于组),但我无法同时进行更新工作:
$Group = new \MyVendor\MongoBundle\Document\Group();
$User = new \MyVendor\MongoBundle\Document\User();
$User->setGroup($Group);
/** @var \Doctrine\ODM\MongoDB\DocumentManager $dm */
$dm = $this->get('doctrine_mongodb')->getManager();
$dm->persist($Group);
$dm->persist($User);
$dm->flush();
MongoDB 中的结果:
团体
{
"_id": ObjectId("5043e24acdc2929a0500000d"),
}
用户
{
"_id": ObjectId("5043e24acdc2929a0500000c"),
"group": {
"$ref": "Group",
"$id": ObjectId("5043e24acdc2929a0500000d"),
"$db": "my_db"
}
}
src/MyVendor/MongoBundle/Document/User.php
<?php
namespace MyVendor\MongoBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* @MongoDB\Document(repositoryClass="MyVendor\MongoBundle\Repository\UserRepository")
*/
class User
{
/**
* @MongoDB\Id
*/
private $id;
/**
* @var
* @MongoDB\ReferenceOne(targetDocument="Group", inversedBy="users")
*/
private $group;
/**
* Set group
*
* @param MyVendor\MongoBundle\Document\Group $group
* @return User
*/
public function setGroup(\MyVendor\MongoBundle\Document\Group $group)
{
$this->group = $group;
return $this;
}
}
src/MyVendor/MongoBundle/Document/Group.php
<?php
namespace MyVendor\MongoBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* @MongoDB\Document
*/
class Group
{
/**
* @MongoDB\Id
*/
private $id;
/**
* @MongoDB\ReferenceMany(targetDocument="User", mappedBy="group")
* @var User[]
*/
private $users;
public function __construct()
{
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add users
*
* @param MyVendor\MongoBundle\Document\User $users
*/
public function addUsers(\MyVendor\MongoBundle\Document\User $users)
{
$this->users[] = $users;
}
}