2015-06-21 113 views
0

有沒有辦法將ArrayCollection關聯到由實體創建的數據庫列?作爲實體屬性的Symfony數組集合

例如,我有兩個實體:家庭和寵物類型。

家庭當前有一個寵物類型的屬性,但它期望的寵物類型對象,所以只有一個可以在此刻選擇。

我希望家庭能夠擁有多種寵物類型。因此,不必選擇狗或貓,他們可以選擇狗和貓。

我已經試過這樣做,但我得到以下錯誤:

Catchable Fatal Error: Argument 1 passed to Acme\CoreBundle\Entity\Household::setPetType() must be an instance of Acme\CoreBundle\Entity\PetType, instance of Doctrine\Common\Collections\ArrayCollection given

我假設我需要在家庭實體,以改變屬性petType關聯到一個以上的寵物類型?

+2

在你的情況下,實體有多對多關係。 (一個家庭可以有許多PetType和一個PetType可以在許多家庭中)。發佈您的實體類以獲取更多解釋。 – jagad89

+0

謝謝。我通常會發布儘可能多的代碼,但是這個項目中有一個NDA,所以我不確定我可以透露多少信息。使用你的輸入和下面的答案,我能夠得到這個工作。謝謝! – matcartmill

回答

1

從描述看來,HouseholdPetType的基數爲m-to-one;這意味着家庭記錄可能只有一個PetType,而PetType可能與多個Household記錄關聯。

從DB的角度來看,表示外鍵爲Household表。如果您想在HouseholdPetType之間建立「多重」連接,則必須修改實體之間的關係。

只是一個例子(免責聲明:您的實體可能有不同的名稱,我沒有測試此代碼,我在這裏解釋一個概念,上可運行的代碼不工作作爲你的例子並不具有片段的例子來)

class Household 
{ 
    //some properties 

    /** 
    * @ORM\ManyToMany(targetEntity="PetType", inversedBy="households") 
    * @ORM\JoinTable(name="household_pettype") 
    */ 
    $pet_types; 

    //some methods 

    public function addPetType(PetType $petType) 
    { 
    $this->pet_types[] = $petType; 

    return $this; 
    } 

    public function setPetTypes(ArrayCollection $petTypes) 
    { 
    $this->pet_types = $petTypes; 

    return $this; 
    } 

    public function removePetType(PetType $petType) 
    { 
    $this->pet_types->removeElement($petType); 
    } 

    public function getPetTypes() 
    { 
    return $this->pet_types; 
    } 
} 

class PetType 
{ 
    //some properties 

    /** 
    * @ORM\ManyToMany(targetEntity="Household", mappedBy="pet_types") 
    */ 
    $households; 

    //some methods 

    public function addHousehold(Household $household) 
    { 
    $this->households[] = $household; 

    return $this; 
    } 

    public function setHouseholds(ArrayCollection $households) 
    { 
    $this->households = $households; 

    return $this; 
    } 

    public function removeHousehold(Household $household) 
    { 
    $this->households->removeElement($household); 
    } 

    public function getHousehold() 
    { 
    return $this->households; 
    } 
} 

之後,你需要再次運行

php app/consolle doctrine:schema:update --force

這將更新你的DB模式,因爲新的基數是米對N,將創建一個名爲household_pettype關係表(將舉行從其他兩個表只有外鍵)

之後,你可以可替代地使用兩種方法(從視圖家庭點)

  • ->addPetType($petType);,將一個PetType對象追加到 Household收集
  • ->setPetTypes($petTypeArrayCollection);,將在拍攝所有設置PetTypes
+0

謝謝!我想了很多。我99%確定我需要關係表,但只是想驗證。我已經通過實現答案中的許多元素來獲得解決方案。 – matcartmill