2012-03-22 64 views
2

我目前的Client-Entity有一個卸載區和一個加載區,它們都是ClientArea-Entities。Symfony2/Doctrine2一對多兩次相同的對象

namespace ACME\DemoBundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 
use Sorien\DataGridBundle\Grid\Mapping as GRID; 
use Symfony\Component\Validator\Constraints as Assert; 
use Doctrine\Common\Collections\ArrayCollection; 

/** 
* ACME\DemoBundle\Entity\Client 
* 
* @ORM\Table() 
* @ORM\Entity(repositoryClass="ACME\DemoBundle\Entity\ClientRepository") 
*/ 
class Client 
{ 
enter code here/** 
* @ORM\OneToMany(targetEntity="ClientArea",mappedBy="client", cascade={"persist", "remove"}) 
*/ 
public $unloading_areas; 

/** 
* @ORM\OneToMany(targetEntity="ClientArea",mappedBy="client", cascade={"persist", "remove"}) 
*/ 
public $loading_areas; 
} 

_

class ClientArea 
{ 
    /** 
    * @ORM\ManyToOne(targetEntity="Client") 
    */ 
    public $client; 
} 

這不起作用,因爲客戶端只能映射1名關聯。 如何正確映射關係?

回答

1

要創建實體關係,您需要在連接表時使用鍵。你的客戶端類應該有定義的id鍵,你需要初始化集合,這樣的:

class Client 
{ 
    //.... 

    /** 
    * @var integer $id 
    * 
    * @ORM\Column(name="id", type="integer", nullable=false) 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="IDENTITY") 
    */ 
    private $id; 

    /** 
    * @ORM\OneToMany(targetEntity="ClientArea", mappedBy="client", cascade={"persist", "remove"}) 
    */ 
    public $unloading_areas; 

    /** 
    * @ORM\OneToMany(targetEntity="ClientArea", mappedBy="client", cascade={"persist", "remove"}) 
    */ 
    public $loading_areas; 

    public function __construct() { 
     // Initialize collections 
     $this->unloading_areas = new \Doctrine\Common\Collections\ArrayCollection(); 
     $this->loading_areas = new \Doctrine\Common\Collections\ArrayCollection(); 
    } 

    // .... 
} 

你ClientArea類應該再是這個樣子:

class ClientArea 
{ 
    // .... 

    /** 
    * @ORM\Column(name="client_id", type="int", nullable=false) 
    */ 
    private $clientId; 

    /** 
    * @ORM\ManyToOne(targetEntity="Client") 
    * @JoinColumn(name="client_id", referencedColumnName="id") 
    */ 
    public $client; 

    // .... 
} 

現在,這兩個實體應正確映射。 要了解更多關於學說中的關聯映射,請閱讀文章:http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/association-mapping.html

希望這會有所幫助。