【问题标题】:Doctrine ODM with MongoDB need both reference mappings setDoctrine ODM with MongoDB 需要两个参考映射集
【发布时间】:2013-12-09 13:28:59
【问题描述】:

我在使用 MongoDB 和 Symfony 2.x 的原则 ODM 中遇到以下情况

A类:

class Port extends AbstractEthernetPort
{
/** Other Fields **/

/**
 * Owning the reference
 * @MongoDB\ReferenceOne(
 *     targetDocument="\xxx\AbstractObject",
 *     cascade="all",
 *     inversedBy="ports"
 * )
 */
protected $device;

/** SETTER and GETTERS **/

}

B类:

class Device extends AbstractObject
{
/** Other Fields **/

/**
 * @MongoDB\ReferenceMany(
 *     targetDocument="\xxx\AbstractEthernetPort",
 *     cascade="all",
 *     mappedBy="device"
 * )
 */
protected $ports = array();

/** SETTER and GETTERS **/
}

这两个类都与 ReferenceOne 和 ReferenceMany 链接在一起。这篇文章的代码略有改动。

这是测试用例的两个版本。第一个不起作用,第二个起作用:

    public function testPorts() {
    $dm = self::$container->get('doctrine_mongodb')->getManager();

    $sideASwitch = new Device();
    $sideASwitch->setName("Switch01");

    $copper1 = new Port();
    $copper1->setDescription("Copper Port");

    $copper2 = new Port();
    $copper2->setDescription("Copper Port");

    $sideASwitch->setPorts(array($copper1, $copper2));

    $dm->persist($sideASwitch);

    $dm->flush();

    $x = $dm->getRepository("Device")->findOneBy(array());
    \Doctrine\Common\Util\Debug::dump($x,1);
    }

最后的查询返回一个内容为0的ports数组。

    public function testPorts() {
    $dm = self::$container->get('doctrine_mongodb')->getManager();

    $sideASwitch = new Device();
    $sideASwitch->setName("Switch01");

    $copper1 = new Port();
    $copper1->setDescription("Copper Port");

    $copper2 = new Port();
    $copper2->setDescription("Copper Port");

    // ADDITIONAL
    $copper1->setDevice($sideASwitch);
    $copper2->setDevice($sideASwitch);

    $sideASwitch->setPorts(array($copper1, $copper2));

    $dm->persist($sideASwitch);

    $dm->flush();

    $x = $dm->getRepository("Device")->findOneBy(array());
    \Doctrine\Common\Util\Debug::dump($x,1);
    }

此查询返回一个包含 2 个对象的端口数组...

这是 Doctrine ODM 中的正常行为还是我做错了什么?

感谢您的帮助

【问题讨论】:

    标签: mongodb orm doctrine mapping doctrine-odm


    【解决方案1】:

    这是预期的行为。调用$sideASwitch->setPorts(array($copper1, $copper2)); 无效,因为ports 是映射端。

    为方便起见,我经常在映射 (Device) 端执行以下操作:

    public function setPorts(array $ports)
    {
        foreach($ports as $port) {
            $port->setDevice($this);
        }
    
        return $this;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      相关资源
      最近更新 更多