從描述看來,Household
和PetType
的基數爲m-to-one;這意味着家庭記錄可能只有一個PetType
,而PetType
可能與多個Household
記錄關聯。
從DB的角度來看,表示外鍵爲Household
表。如果您想在Household
和PetType
之間建立「多重」連接,則必須修改實體之間的關係。
只是一個例子(免責聲明:您的實體可能有不同的名稱,我沒有測試此代碼,我在這裏解釋一個概念,上可運行的代碼不工作作爲你的例子並不具有片段的例子來)
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
在你的情況下,實體有多對多關係。 (一個家庭可以有許多PetType和一個PetType可以在許多家庭中)。發佈您的實體類以獲取更多解釋。 – jagad89
謝謝。我通常會發布儘可能多的代碼,但是這個項目中有一個NDA,所以我不確定我可以透露多少信息。使用你的輸入和下面的答案,我能夠得到這個工作。謝謝! – matcartmill