Doctrine2 是否有命名范围的类似物?

发布于 2024-10-02 05:46:10 字数 168 浏览 12 评论 0原文

Doctrine2 是否具有与 ActiveRecord 类似的功能 命名范围

Does Doctrine2 have a features similar to ActiveRecord's named scopes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷弦 2024-10-09 05:46:10

D2 中没有内置系统,但使用 Doctrine 2 的 QueryBuilder 类,它允许您使用更具编程性的方法分段构造查询。

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

看来 Yii 的实现将查询条件存储在数组中,并且在使用命名范围时将它们注入到查询中。您可以轻松执行类似的操作,返回预加载这些参数的 QueryBuilder 对象。

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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文