我有一个用户实体,我试图从UserService更新它。当我尝试更新设置为数组集合的属性时,问题就出现了。如何在Doctrine 2中使用OneToMany关系更新记录?
/**
*
* @param \Doctring\Common\Collections\Collection $property
* @OneToMany(targetEntity="Countries",mappedBy="user", cascade={"persist", "remove"})
*/
private $countries;
我不知道如果我应该以某种方式删除所有$国家之前,我把他们回来,或者如果有一种方法来选择要删除,并成立了其中不同的....这是我的updateUser方法看起来如此:
public function updateUser($user) {
$entity = $this->getUser($user['id']);
if (!$entity)
throw new Exception('Error saving user!');
$countries = $this->getCountriesArray($user); //countries already set in the db
$tempCountries = array();
$delete = array();
foreach ($countries as $country) {
$found = false;
if (in_array($country, $user['countries'])) {
$tempCountries[] = $country;
} else {
$delete[] = $country;
}
}
$tempCountries = array_unique(array_merge( //combine the countries from the db we want to leave
$tempCountries, //with those the user selected
$user['countries']));
...
//here I need something to remove the countries in $delete...right?
...
$entity->setEmail($user['email']);
$entity->setResponsable($user['responsable']);
$entity->setPassword($this->createPass($user['password']));
$entity->setUrl($user['url']);
$entity->setRole($user['role']);
$modelCountries = array();
foreach($tempCountries as $c) {
$p = new Countries();
$p->setCountryName($c);
$p->setUser($entity);
$modelCountries[] = $p;
}
$entity->setCountries($modelCountries);
$this->em->persist($entity);
$this->em->flush();
}
请stackOverflow ...给我一只手,使这个意义。
好吧,我不想在我的脑袋太多这一点,它只是一个测试应用程序...试图找出教义2是如何工作的......我可以通过执行'$ entity-> getCountries();'来获得与实体相关的所有国家,但是如何删除它们? –