2013-12-09 66 views
0

我具有教義ODM以下情況與MongoDB的和Symfony的2.x的學說ODM與MongoDB中需要兩個參考映射設置

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個內容的端口數組。

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個對象...

這是在教義ODM正常行爲或者我做錯了什麼?

感謝您的任何幫助

回答

0

這是預期的行爲。調用$sideASwitch->setPorts(array($copper1, $copper2));不起作用,因爲ports是映射端。

爲方便起見,我經常做類似的映射(Device)側以下幾點:

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

    return $this; 
}