加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何使用Doctrine的ArrayCollection :: exists方法

发布时间:2020-12-13 13:33:54 所属栏目:PHP教程 来源:网络整理
导读:我必须检查ArrayCollection中是否已存在Email实体,但我必须将电子邮件检查为字符串(实体包含ID以及与其他entites的某些关系,因此我使用单独的表来保留所有电子邮件). 现在,在第一次我写了这段代码: /** * A new Email is adding: check if it already exist
我必须检查ArrayCollection中是否已存在Email实体,但我必须将电子邮件检查为字符串(实体包含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;
        }
    }

但是阅读ArrayCollection类我看到了方法exists,这似乎是我做同样事情的一种更加优雅的方式.

但我不知道如何使用它:有人可以解释我如何使用这个方法给出上面的代码?

当然,在PHP中,Closure是一个简单的 Anonymous functions.您可以重写您的代码如下:
$exists =  $this->emails->exists(function($key,$element) use ($email){
        return $email->getEmail() === $element->getEmail()->getEmail();
        }
    );

希望这有帮助

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读