我有一个用户实体,我正在尝试从UserService更新它。当我尝试更新设置为数组集合的属性时出现问题。
/**
*
* @param \Doctring\Common\Collections\Collection $property
* @OneToMany(targetEntity="Countries",mappedBy="user", cascade={"persist", "remove"})
*/
private $countries;
我不确定在设置它们之前我是否应该以某种方式删除所有$ country或者是否有办法选择删除哪些并设置不同的....这就是我的意思到目前为止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 ...让我从中了解一下。
答案 0 :(得分:0)
这实际上取决于您的使用案例。
正如您所说,您可以在删除所有国家/地区之前设置新的国家/地区,或者计算增量值,并仅更新所需的国家/地区。
计算delta,然后UPDATE可能会非常棘手和困难,在大多数情况下,你最好只想删除all和INSERT。
答案 1 :(得分:0)
对于我当前和个人的选择,我使用DQL删除映射实体的所有欠侧行,然后插入新的。
class Rule
{
/**
* @OneToMany(targetEntity="Tier", mappedBy="rule", cascade={"persist", "remove"})
* @JoinColumn(name="ruleId", referencedColumnName="ruleId")
* @var Tier[]
*/
public $tiers;
因此,当我在通话中传递新Tier时,我只是从Rule Mapper中删除该角色的所有层
public function resetTiers($ruleId)
{
$modelClass = "Tier";
$q = $this->doctrineEntityManager->createQuery("Delete from $modelClass m where m.rule =" . $ruleId);
$numDeleted = $q->execute();
return $numDeleted;
}
然后调用通常的
$this->doctrineEntityManager->persist($rule);
$this->doctrineEntityManager->flush();
希望有所帮助