2011-06-23 92 views
1

我有一个用户实体,我试图从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 ...给我一只手,使这个意义。

回答

0

它实际上取决于你的用例。如上所述,您可以先删除所有国家以设置新的国家,或者计算增量,然后只更新所需的国家。

  • 您提供哪些国家的服务?三角洲?还是完整列表?
  • 你有性能限制吗?如果是的话,DELETE语句与SELECT然后UPDATE的成本是多少?

计算增量,然后更新可能会非常棘手和困难,在大多数情况下,你最好只想删除所有和INSERT。

+0

好吧,我不想在我的脑袋太多这一点,它只是一个测试应用程序...试图找出教义2是如何工作的......我可以通过执行'$ entity-> getCountries();'来获得与实体相关的所有国家,但是如何删除它们? –

0

对于我目前和个人的选择,我正在使用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();

希望有帮助

相关问题