Query Builder and Group By on two columns in Symfo

2019-06-15 00:00发布

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
;

If I have 3 entries, for exemple:

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

I expect:

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

But I get:

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

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

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

EDIT:

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

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-15 00:26

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
;

:)

查看更多
淡お忘
3楼-- · 2019-06-15 00:39

Try the following its by using doctrine DQL method -

$query = $em->createQuery("SELECT m.id, m.from_id as c, m.to_id as c FROM AcmeDemoBunlde:Message as m WHERE m.c = 1 GROUP BY m.from_id, m.to_id"); 

$messageDetails = $query->getResult(); 

Instead of AcmeDemoBundle replace with your appropriate bundle name.

查看更多
登录 后发表回答