查询生成器和分组在Symfony2 / Doctrine中的两列产生重复 [英] Query Builder and Group By on two columns in Symfony2 / Doctrine generate duplicates

查看:115
本文介绍了查询生成器和分组在Symfony2 / Doctrine中的两列产生重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个消息包,其中消息按联系人分组。在我的索引页面上,我显示不同的线程。当您在一个线程上,它显示您和您的联系人之间交换的所有消息。我使用查询生成器来显示索引页面上的线程:

I'm creating a message bundle where messages are grouped per contacts. On my index page, I display different threads. When you clic on one thread, it show all the messages exchanged between you and your contact. I use a Query Builder to display the threads on my index page:

$qb = $this->createQueryBuilder('m')
    ->where('m.from = ?1 or m.to = ?1')
    ->groupBy('m.to, m.from')
    ->orderBy('m.date', 'DESC')
    ->setParameter(1, $user->getId())
    ->setMaxResults($pagination) // limit
    ->setFirstResult($pagination * $page) // offset
;

如果我有3个条目,例如:

If I have 3 entries, for exemple:

+----+------+----+
| id | from | to |
+----+------+----+
| 1  | 1    | 2  |
+----+------+----+
| 2  | 2    | 1  |
+----+------+----+
| 3  | 1    | 2  |
+----+------+----+

我期望:

+----+------+----+
| id | from | to |
+----+------+----+
| 3  | 1    | 2  |
+----+------+----+

但是我得到:

+----+------+----+
| id | from | to |
+----+------+----+
| 2  | 2    | 1  |
+----+------+----+
| 3  | 1    | 2  |
+----+------+----+

我发现了一种方式来使用SQL,对于from_id和to_id使用相同的别名:

I found a way to do it with SQL, using the same alias for from_id and to_id:

SELECT id, from_id as c, to_id as c FROM Message WHERE c = 1 GROUP BY from_id, to_id

但是我不知道如何使用Doctrine。

But I don't know how to do it with Doctrine.

编辑:

直到我得到一个更好的主意,我使用一个键轻松地分组。

Until I get a better idea, I use a key to easily "group by".

// entity

/**
* @ORM\Column(name="key", type="string", length=40)
*/
private $key;

/**
 * @ORM\PrePersist()
 */
public function setOnPrePersist()
{
    if($this->from < $this->to) {
        $key = $this->from . 't' . $this->to;
    } else {
        $key = $this->to . 't' . $this->from;
    }

    $this->key = $key;
}

// query builder

$qb = $this->createQueryBuilder('m')
    ->where('m.from = ?1 or m.to = ?1')
    ->groupBy('m.key')
    ->orderBy('m.date', 'DESC')
    ->setParameter(1, $user->getId())
    ->setMaxResults($pagination) // limit
    ->setFirstResult($pagination * $page) // offset
;

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


推荐答案

如果您在group by 你必须使用addGroupBy()方法。

in case that you have many columns in 'group by' you must use addGroupBy() method.

$qb = $this->createQueryBuilder('m')
    ->where('m.from = ?1 or m.to = ?1')
    ->groupBy('m.to')
    ->addGroupBy('m.from')
    ->orderBy('m.date', 'DESC')
    ->setParameter(1, $user->getId())
    ->setMaxResults($pagination) // limit
    ->setFirstResult($pagination * $page) // offset
;

:)

这篇关于查询生成器和分组在Symfony2 / Doctrine中的两列产生重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆