我有一個用戶實體,我試圖從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();'來獲得與實體相關的所有國家,但是如何刪除它們? –