开发者

Is there named scope's analog for Doctrine2?

开发者 https://www.devze.com 2023-01-24 20:46 出处:网络
Does Doctrine2 have a features similar to ActiveRecord\'s named scopes?开发者_如何学GoThere isn\'t one baked into D2, but it probably wouldn\'t be too much of a stretch to implement a system similar t

Does Doctrine2 have a features similar to ActiveRecord's named scopes?开发者_如何学Go


There isn't one baked into D2, but it probably wouldn't be too much of a stretch to implement a system similar to Yii's using Doctrine 2's QueryBuilder class, which allows you to construct a query in pieces, using a more programmatic approach.

 $qb = $em->createQueryBuilder;
 $qb->select('u')
    ->from('User', 'u')
    ->where('active IS NOT NULL);

It appears that Yii's implementation stores query criteria in an array, and they are injected into the query when a named scope is used. You could easily do something similar that returns a QueryBuilder object with those params pre-loaded.

class UserRepository extends EntityRepository
{
   private $_namedScopes;

   public getActiveUsersWhoLoggedInLastWeek()
   {
      // return a query builder for this model
      $qb = $this->_namedScopes->initScope();

      // start adding pre-defined criteria
      $qb = $this->_namedScopes->addScope($qb, 'active')
      $qb = $this->_namedScopes->addScope($qb, 'lastWeek');

      return $qb->getQuery()->getResult();
   }
}

There are probably several different ways to approach this, so that's just one quick example. The hard part would probably be figuring out how to handle criteria collisions.


http://www.doctrine-project.org/jira/browse/DDC-750

0

精彩评论

暂无评论...
验证码 换一张
取 消