加入收藏 | 设为首页 | 会员中心 | 我要投稿 莱芜站长网 (https://www.0634zz.com/)- 云连接、建站、智能边缘云、设备管理、大数据!
当前位置: 首页 > 编程开发 > PHP > 正文

php – Symfony中关联实体集合的高级过滤

发布时间:2020-08-16 06:03:23 所属栏目:PHP 来源:互联网
导读:如果我有一个关联的实体是一个集合,你在获取时有什么选择? 例如假设我有一个带有此定义的$view实体: /** * @ORMOneToMany(targetEntity=GutensiteCmsBundleEntityViewViewVersion, mappedBy=entity) * @ORMOrderBy({timeMod = DESC}) */prot

如果我有一个关联的实体是一个集合,你在获取时有什么选择?

例如假设我有一个带有此定义的$view实体:

/**
 * @ORMOneToMany(targetEntity="GutensiteCmsBundleEntityViewViewVersion",mappedBy="entity")
 * @ORMOrderBy({"timeMod" = "DESC"})
 */
protected $versions;

public function getVersions() {
    return $this->versions;
}

我希望得到与实体相关的所有版本,如下所示:

$view->getVersions();

这将返回一个集合.大.但是有可能采取该集合并按标准过滤它,例如比某个日期更新?或者按一些(其他)标准订购?

或者此时您只是希望对存储库进行查询:

$versions = $em->getRepository("GutensiteCmsBundle:ViewViewVersion")->findBy(array(
    array(
        'viewId',$view->getId(),'timeMod',time()-3600
    )
    // order by
    array('timeMod','DESC')
));
最新版本的Doctrine中有一个令人惊讶的未知功能,它使这些查询更容易.

它似乎没有名称,但您可以在9.8 Filtering Collections的Doctrine文档中阅读它.

Collections have a filtering API that allows to slice parts of data from a collection. If the collection has not been loaded from the database yet,the filtering API can work on the SQL level to make optimized access to large collections.

在您的情况下,您可以在View实体上编写这样的方法.

use DoctrineCommonCollectionsCriteria;

class View {
  // ...

  public function getVersionsNewerThan(DateTime $time) {
    $newerCriteria = Criteria::create()
      ->where(Criteria::expr()->gt("timeMod",$time));

    return $this->getVersions()->matching($newerCriteria);
  }
}

这将做两件事之一:

>如果集合是水合的,它将使用PHP来过滤现有的集合.
>如果集合没有水合,它将使用SQL约束从数据库中获取部分集合.

这真的很棒,因为将存储库方法连接到您的视图通常是混乱的并且容易中断.

我也喜欢@ igor-pantovic的回答,虽然我已经看到这种方法会导致一些有趣的错误.

(编辑:莱芜站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读