【问题标题】:How can I limit an associated entity result in Doctrine2?如何在 Doctrine2 中限制关联实体结果?
【发布时间】:2011-09-01 10:53:22
【问题描述】:

我有以下疑问:

$query = $this->getEntityManager()->createQuery('
                      SELECT u, p, m
                      FROM MyCoreBundle:User u
                      JOIN u.programmes p
                      JOIN u.motivation m
                      ');

$result = $query->getResult();

我想限制为每个用户返回的动机对象是我在其他地方使用的第二个查询的结果(在动机存储库上):

$query = $this->getEntityManager()->createQuery('
                      SELECT m FROM MyCoreBundle:Motivation m
                      WHERE m.user = :user
                      ORDER BY m.date DESC');

$query->setParameter('user',$user);
$query->setFirstResult(0);
$query->setMaxResults(1);
//@TODO if there is not result recorded for the user, return sth which indicates this
return $query->getResult();

有没有办法限制和限制第一次查询中的动机或更好的方法?

【问题讨论】:

  • 考虑到下面写的,并假设“最新动机”对你来说是最重要的并且会被很多人访问,可能的解决方案是创建User:LatestMotivation OneToOne 关系。然后每次添加一个新的 Motivation 实体时,(通过 Doctrine prePersist 事件)用新添加的实体更新 LatestMotivation。这样,您将能够遍历许多 User 记录以获取最新动机。 HTH

标签: php doctrine-orm symfony


【解决方案1】:

你不能限制联合行数。

如果你有 Doctrine 2.1,你可以在集合上使用 ->slice()

$collection = $user->getMotivations();    // returns a LazyCollection, 
                                          // makes no SQL query

$motivations = $collection->slice(0, 20); // queries the first 20 motivations 
                                          // for this user (if the association
                                          // was not fetch-joint)

http://www.doctrine-project.org/docs/orm/2.0/en/tutorials/extra-lazy-associations.html

【讨论】:

  • 谢谢 - 我通过向我的用户实体添加另一个方法来解决它,该方法只添加一个动机条目,循环对象并覆盖 $motivation 属性。很脏,但它可以工作。
  • @amaud576875 不幸的是,切片方法仅为当前用户初始化关联。如果您遍历多个用户,则会产生多个查询。有没有办法为所有用户获取切片集合?
  • @PetrPeller 我有类似的问题。你解决了吗?
  • @svlada 还没有。想知道 Doctrine 2.2 中是否有可以提供帮助的更改。你找到什么了吗?
  • @arnaud576875 slice() 方法似乎很酷,但有两个陷阱:1) 关联 User.motivations 应声明为 fetch="EXTRA_LAZY"。如果您将其保留为默认值"LAZY",那么所有动机都将从 DB 中查询然后切片,而不是仅查询 20。2)queries the first 20 motivations 有点模糊......通常用于解决您的域任务您可能想要最新的 20 个动机,例如ORDER BY m.date DESCslice() 不提供对它们进行排序的机会。因此,尽管我很高兴找到slice(),但它很快就不适合解决实际问题
猜你喜欢
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 2012-05-31
相关资源
最近更新 更多