php - 如何限制 Doctrine2 中的关联实体结果?

标签 php doctrine-orm symfony

我有以下查询:

$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();

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

最佳答案

您不能限制联合行数。

如果你有 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

关于php - 如何限制 Doctrine2 中的关联实体结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7269298/

相关文章:

php - 调用 array_unique 后删除未定义的数组索引

php - 无法从数据库中获取当前月份和年份

php - 如何获取来自另一个域的json数据?

php - 制作视频 "watch page"

php - 教义2 : OneToMany relation

php - 学说一对一关系映射

symfony - 如何禁用带有注释的 Doctrine 持久级联?

php - 交响乐/主义 : Getting the first maximum value from database

php - 在 symfony 文件上传中获取图像尺寸

未找到 PHPDox 文件