问题描述
|
我有一个用户实体,我正在尝试从UserService更新它。当我尝试更新设置为数组集合的属性时,问题就来了。
/**
*
* @param \\Doctring\\Common\\Collections\\Collection $property
* @OnetoMany(targetEntity=\"Countries\",mappedBy=\"user\",cascade={\"persist\",\"remove\"})
*/
private $countries;
我不确定是否应该在重新设置$ countries之前以某种方式删除所有$ countries,或者是否有办法选择要删除的$ countries并设置不同的$ 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 ...给我一些帮助。
解决方法
它实际上取决于您的用例。
如您所说,您可以在设置新国家之前删除所有国家,或者计算增量并仅更新所需的国家。
您正在向哪些国家提供服务?三角洲?还是完整列表?
您是否有性能限制?如果是,那么DELETE语句与SELECT然后是UPDATE的开销是多少?
计算增量,然后进行更新可能会很棘手和困难,在大多数情况下,您最好只删除全部并插入。
, 对于我当前和个人的选择,我正在使用DQL删除映射实体的所有欠侧行,然后插入新的。
class Rule
{
/**
* @OneToMany(targetEntity=\"Tier\",mappedBy=\"rule\",cascade={\"persist\",\"remove\"})
* @JoinColumn(name=\"ruleId\",referencedColumnName=\"ruleId\")
* @var Tier[]
*/
public $tiers;
因此,当我在通话中传递新层时,我只是从规则映射器中删除该角色的所有层
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();
希望能有所帮助