Aer*_*dir 12 php doctrine symfony doctrine-orm
我必须检查一个Email实体是否已经存在ArrayCollection但我必须对电子邮件进行检查作为字符串(实体包含一个ID和一些与其他entites的关系,因此我使用一个单独的表来保存所有电子邮件).
现在,在第一次我写这个代码:
/**
* A new Email is adding: check if it already exists.
*
* In a normal scenario we should use $this->emails->contains().
* But it is possible the email comes from the setPrimaryEmail method.
* In this case, the object is created from scratch and so it is possible it contains a string email that is
* already present but that is not recognizable as the Email object that contains it is created from scratch.
*
* So we hav to compare Email by Email the string value to check if it already exists: if it exists, then we use
* the already present Email object, instead we can persist the new one securely.
*
* @var Email $existentEmail
*/
foreach ($this->emails as $existentEmail) {
if ($existentEmail->getEmail()->getEmail() === $email->getEmail()) {
// If the two email compared as strings are equals, set the passed email as the already existent one.
$email = $existentEmail;
}
}
Run Code Online (Sandbox Code Playgroud)
但阅读ArrayCollection课程后,我看到的方法exists似乎是一种更加优雅的方式来做同样的事情.
但我不知道如何使用它:有人可以解释我如何使用这个方法给出上面的代码?
Mat*_*teo 23
当然,在PHP中,Closure是一个简单的匿名函数.您可以按如下方式重写代码:
$exists = $this->emails->exists(function($key, $element) use ($email){
return $email->getEmail() === $element->getEmail()->getEmail();
}
);
Run Code Online (Sandbox Code Playgroud)
希望这有帮助
| 归档时间: |
|
| 查看次数: |
9888 次 |
| 最近记录: |