在Doctrine2中检查关系是否存在的技巧2 [英] Techniques to check if relationship exists in Doctrine2

查看:102
本文介绍了在Doctrine2中检查关系是否存在的技巧2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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



在Doctrine 1.x中有一个叫存在可以在一个实体上调用以检查:



http://www.doctrine-project.org/documentation/手册/ 1_2 / en / work-with-models#交易关系:结算相关记录



在Doctrine 2.0中,这是我'我们往往会这样做。其他人使用什么技术?

   
class Group {
私人$ id;
protected $ name;
protected $ users;

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

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


解决方案

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



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

  / ** 
*检查收集是否为空。
*
*注意:这比count()== 0.优先。
*
* @return boolean如果集合为空,则为TRUE,否则为FALSE。
* /
public function isEmpty()
{
return! $这 - > _elements;
}

所以从我的例子

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


I can't seem to find any mention in the Doctrine documentation on how to check if an entity has an existing relationship to another entity:

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

In Doctrine 1.x there was a method called exists that could be called on an entity to check this:

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

In Doctrine 2.0 this is what I've tended to do. What techniques are other people using?

<?php

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

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

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

解决方案

Well - I actually stumbled on the correct answer today while looking though the ArrayCollection class. You should use the 'isEmpty' method.

From the code (the comments are theirs, not mine)

/**
 * 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;
}

So from my example

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

这篇关于在Doctrine2中检查关系是否存在的技巧2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆