2013-10-21 34 views
4

我有以下兩個類別,它們具有ManyToMany關係並保存在名爲countries_involved的連接表中。在原則中查詢加入表格

class CountriesInvolved 
{ 
/** 
* @var integer 
*/ 
private $id; 

/** 
* @var string 
*/ 
private $description; 

/** 
* @var \DateTime 
*/ 
private $createdAt; 

/** 
* @var \DateTime 
*/ 
private $updatedAt; 

/** 
* @var \ACME\SouthBundle\Entity\Country 
*/ 
private $country; 

/** 
* @var \Doctrine\Common\Collections\Collection 
*/ 
private $involvement; 
} 

class Involvement 
{ 
/** 
* @var integer 
*/ 
private $id; 

/** 
* @var string 
*/ 
private $name; 

/** 
* @var string 
*/ 
private $description; 
} 

的關係是陽明

manyToMany: 
    involvement: 
     targetEntity: Involvement 
     joinTable: 
      name: countries_involvement 
      joinColumns: 
       case_country_involved_id: 
        referencedColumnName: id 
      inverseJoinColumns: 
       involvement_id: 
        referencedColumnName: id 

我試圖返回基於一個參與的ID,但那種參與國家的結果定義如下停留在寫入查詢而沒有出現錯誤。以下是我試過到目前爲止:

$em = $this->getDoctrine()->getManager()->createQueryBuilder(); 
    $q = $em->select('c') 
    ->from('ACMESouthBundle:CountriesInvolved','c') 
    ->innerJOIN('c.Involvement','i') 
    ->where('i.id = 1') 
    ->groupBy('c.country')->getQuery(); 

的錯誤是:

[Semantical Error] line 0, col 80 near 'i WHERE i.id': Error: Class ACME\SouthBundle\Entity\CountriesInvolved has no association named Involvement 

回答

9

首先,我會建議使用註釋,你的代碼會更加可讀

我認爲的問題是,您已經忘記了inversedBymappedBy屬性。

以下代碼是使用註釋解決您問題的可能解決方案。

您應該將此代碼添加到Involvement實體:

/** 
* @ORM\ManyToMany(targetEntity="CountriesInvolved", inversedBy="involvement") 
* @ORM\JoinTable(name="countries_involvement", 
*  joinColumns={@ORM\JoinColumn(name="case_country_involved_id", referencedColumnName="id")}, 
*  inverseJoinColumns={@ORM\JoinColumn(name="involvement_id", referencedColumnName="id")} 
*  ) 
*/ 
private $countries; 

CountriesInvolved實體,你應該在$involvement添加以下注釋:

/** 
* @ORM\ManyToMany(targetEntity="Involvement", mappedBy="countries") 
*/ 
private $involvement; 

我剛纔重寫查詢,像這樣:

$em = $this->getEntityManager(); 

$query = $em->createQuery(' 
    SELECT c 
    FROM ACMESouthBundle:CountriesInvolved c 
    JOIN c.involvement i 
    WHERE i.id = :id 
'); 

$query->setParameter('id', '1'); 

return $query->getResult(); 

編輯

這是YAML方法:

CountriesInvolved: 
    manyToMany: 
     involvement: 
      targetEntity: Involvement 
      mappedBy: countries 

CountriesInvolved: 
    manyToMany: 
     countries: 
      targetEntity: CountriesInvolved 
      inversedBy: involvement 
      joinTable: 
       name: countries_involvement 
       joinColumns: 
        case_country_involved_id: 
         referencedColumnName: id 
       inverseJoinColumns: 
        involvement_id: 
         referencedColumnName: id 
+0

對不起我,而不是使用註釋YML但您的解決方案工作就像一個魅力。我想知道我哪裏錯了,因爲我有同樣的事情,但有涉及CountriesInvolved的關係 –

+2

我剛剛更新了答案。注意'inversedBy'和'MappedBy'語句。希望這可以幫助 ;)。 – 2013-10-21 11:45:13