Doctrine 如何在原则2中用一对一关系更新记录?
我有一个用户实体,我正试图从UserService更新它。当我尝试更新设置为数组集合的属性时,问题就出现了Doctrine 如何在原则2中用一对一关系更新记录?,doctrine,doctrine-orm,one-to-many,Doctrine,Doctrine Orm,One To Many,我有一个用户实体,我正试图从UserService更新它。当我尝试更新设置为数组集合的属性时,问题就出现了 /** * * @param \Doctring\Common\Collections\Collection $property * @OneToMany(targetEntity="Countries",mappedBy="user", cascade={"persist", "remove"}) */ private $countries; 我不确定我是否应该在设置之前以某
/**
*
* @param \Doctring\Common\Collections\Collection $property
* @OneToMany(targetEntity="Countries",mappedBy="user", cascade={"persist", "remove"})
*/
private $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();
}
请帮我。。。请帮我解释一下。这实际上取决于您的用例 正如您所说,您可以删除之前的所有国家以设置新的国家,或者计算增量,并仅更新所需的国家
- 您为您的服务提供哪些国家/地区?三角洲?还是完整的名单
- 您有性能限制吗?如果是,删除语句与选择然后更新的成本是多少
计算增量,然后更新可能会很棘手和困难,在大多数情况下,您最好只删除所有并插入。对于我当前和个人的选择,我使用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();
希望这能有所帮助好吧,我不想在这一点上伤脑筋,这只是一个测试应用程序…试图弄清楚条令2是如何工作的。。。通过执行
$entity->getCountries(),我可以获得与实体相关的所有国家/地区代码>但我如何删除它们?