有没有办法将 ArrayCollection 关联到实体创建的数据库列?
例如,我有两个实体:家庭和宠物类型。
家庭电流具有"宠物类型">属性,但它需要"宠物类型"对象,因此目前只能选择一个对象。
我希望家庭能够拥有多种宠物类型。因此,他们不必在狗或猫之间进行选择,而是可以选择狗和猫。
我尝试这样做,但出现以下错误:
可捕获的致命错误:参数 1 传递给 Acme''CoreBundle''Entity''Household::setPetType(( 必须是 Acme''CoreBundle''Entity''PetType, instance of Doctrine''Common''Collections''ArrayCollection 给定
我假设我需要更改家庭实体中 petType 的属性才能关联到多个宠物类型?
从您的描述来看,Household
和 PetType
的基数为 m 对一; 这意味着家庭记录只能有一个PetType
,而PetType
可以关联到多个Household
记录。
从数据库的角度来看,这意味着外键进入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
这将更新您的数据库架构,并且由于新基数是 m 到 n,因此将创建一个名为 household_pettype
的关系表(该表将仅保存其他两个表中的外键(
之后,您也可以使用两种方法(从家庭角度来看(
- 将
PetType
对象追加到的->addPetType($petType);
Household
收藏 -
->setPetTypes($petTypeArrayCollection);
,将设置在镜头中PetTypes