您要实现的是与joinTable的双向多对多关系。
许多企业可以居住在多个城市,一个城市可以有多个企业。
在多对多关系中,任何一方都可以是拥有方。JoinTable 定义可以省略并具有合理的默认值,但如果您想具体指定它,我将其包含在示例中。
业务(在此示例中:拥有方 = inversedBy = JoinTable 定义)
/**
* @ORM\ManyToMany(targetEntity="Your/Bundle/City", inversedBy="businesses",cascade="{persist,merge}" fetch="EAGER")
* @ORM\JoinTable(name="BusinessCity",
* joinColumns={@JoinColumn(name="business_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="city_id", referencedColumnName="id")}
* )
*/
protected $cities;
public function __construct()
{
$this->cities = new ArrayCollection();
}
public function getCities()
{
return $this->cities;
}
public function setCities(Collection $cities)
{
// using map with closure to have dublicate/type-checking provided by addCity
$this->cities->map(function($city) {
$this->addCity($city);
});
return $this;
}
public function addCity(CityInterface $city)
{
// ... you don't want dublicates in your collection
if (!$this->cities->contains($city)) {
$this->cities->add($city);
}
return $this;
}
public function removeCity(CityInterface $city)
{
$this->cities->removeElement($city);
return $this;
}
// other properties and methods ..
城市(反面 = mappedBy)
/**
* @ORM\ManyToMany(targetEntity="Your/Bundle/Business", mappedBy="cities")
*/
protected $businesses;
// getters & setters ...
// other properties and methods ...