检查Doctrine2中是否存在关系的技巧

时间:2011-06-03 08:41:29

标签: php orm doctrine doctrine-orm

我似乎无法在Doctrine文档中找到关于如何检查实体是否与另一个实体存在关系的任何提及:

http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-associations.html

在Doctrine 1.x中,有一个名为exists的方法可以在实体上调用来检查:

http://www.doctrine-project.org/documentation/manual/1_2/en/working-with-models#dealing-with-relations:clearing-related-records

在Doctrine 2.0中,这是我倾向于做的事情。其他人使用什么技术?

<?php

class Group    {
    private $id;
    protected $name;
    protected $users;

    public function __construct()
    {
        $this->colorgroups = new ArrayCollection();
    }

    public function hasUsers() {
        return count($this->users) > 0;
    } 
}

5 个答案:

答案 0 :(得分:8)

嗯 - 我实际上在查看ArrayCollection类时偶然发现了正确的答案。你应该使用'isEmpty'方法。

从代码中(评论是他们的,不是我的)

/**
 * Checks whether the collection is empty.
 * 
 * Note: This is preferrable over count() == 0.
 *
 * @return boolean TRUE if the collection is empty, FALSE otherwise.
 */
public function isEmpty()
{
    return ! $this->_elements;
}

所以从我的例子

public function hasUsers() {
        return !$this->users->isEmpty();
} 

答案 1 :(得分:6)

Doctrine2使用与Doctrine1.2不同的架构。如果要检查某个组是否有某个与之关联的用户,您应该编写一个方法hasUser(User $user)来确定它:

public function hasUser(User $user) {
    foreach ($this->users as $u) {
        if ($u->equals($user)) {
            return true;
        }
    }

    return false;
}

如果要检查数据库中是否存在关系,则必须执行以下DQL查询:

SELECT 1 FROM MyProject\Entity\Group g WHERE :user MEMBER OF g.users;

:userUser对象。

答案 2 :(得分:5)

你可以使用Exists方法http://www.doctrine-project.org/api/common/2.4/class-Doctrine.Common.Collections.ArrayCollection.html#_exists这样的东西

$someId = 123;
$p = function($key, $element) use ($someId){
     return $element->getId() == $someId;
};

$u->exists($p); //here is your result

答案 3 :(得分:-1)

或者,您可以使用异常处理

try {

$entity = $entity->getAnotherEntity() ; // OneToOne Mapping 

}catch(\Exception $e) {

$entity = null ;

}

P.S更具体的例外可以用来使它更好。

答案 4 :(得分:-2)

我知道这是一个老问题,但它可能对其他人或甚至对你有用。 我认为你在寻找的是relatedExists()方法,你可以在这里找到: http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/working-with-models.html#clearing-related-records

希望它会有用!

相关问题