如何使用Doctrine2有效地计算模型中的相关行 [英] How to efficiently count related rows within a model using Doctrine2

查看:87
本文介绍了如何使用Doctrine2有效地计算模型中的相关行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我读了在这里,在模型中使用实体管理器并不是一个好主意,所以我想知道如何查询数据库以找出没有懒惰加载所有相关的模型并做一个count()。



我还没有真正找到一个很好的答案,但似乎这是一个非常重要的事情?



例如

  class House 
{
/ **
* @var房间
* /
保护$ rooms

public function getRoomCount()
{
//不可以在这里使用实体经理吗?
}
}

class Room
{
//在这里放入的东西
}


解决方案

Doctrine 2将自动获取计数,因为关联属性实际上是Doctrine Collection对象: p>

  public function getRoomCount()
{
return $ this-> rooms-> count();
}

如果您将关联标记为渴望,Doctrine将在您查询时加载房间为房屋实体。如果您将其标记为懒惰(默认),则在您实际访问 $ this-> rooms 属性之前,Doctrine将不会加载房间。



根据Doctrine 2.1,您可以将关联标记为额外的懒惰。这意味着调用 $ this-> rooms-> count()将不会加载房间,它只会发出一个 COUNT 查询到数据库。



您可以在这里阅读关于额外的懒惰集合: http://www.doctrine-project.org/docs/orm/2.1/en/tutorials/extra-lazy-associations.html


I'm pretty new to Doctrine and wondering how to efficiently calculate the number of related objects there are for a particular model object.

I read here that it's not a great idea to use the entity manager within models so I'm wondering how I would query the database to find out without lazy loading all of the related models and doing a count().

I haven't really found a great answer yet, but it seems like this is a pretty fundamental thing?

For example

class House
{
    /**
     * @var Room
     */
    protected $rooms

    public function getRoomCount()
    {
        // Cant use entity manager here?
    }
}

class Room
{
    // Shed loads of stuff in here
}

解决方案

Doctrine 2 will get counts for you automatically as association properties are actually Doctrine Collection objects:

public function getRoomCount() 
{
    return $this->rooms->count();
}

If you mark the association as eager, Doctrine will load the rooms whenever you query for house entities. If you mark them as lazy (the default), Doctrine won't load the rooms until you actually access the $this->rooms property.

As of Doctrine 2.1 you can mark associations as extra lazy. This means that calling $this->rooms->count() won't load the rooms, it will just issue a COUNT query to the database.

You can read about extra lazy collections here: http://www.doctrine-project.org/docs/orm/2.1/en/tutorials/extra-lazy-associations.html

这篇关于如何使用Doctrine2有效地计算模型中的相关行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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