簡體   English   中英

Symfony2 / Doctrine中的兩列上的Query Builder和Group By生成重復項

[英]Query Builder and Group By on two columns in Symfony2 / Doctrine generate duplicates

我正在創建一個消息包,其中消息按聯系人分組。 在我的索引頁面上,我顯示不同的線程。 當您在一個線程上進行clic時,它會顯示您和您的聯系人之間交換的所有消息。 我使用查詢生成器在索引頁面上顯示線程:

$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個條目,例如:

+----+------+----+
| 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的相同別名:

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

但我不知道如何用Doctrine做到這一點。

編輯:

直到我得到一個更好的主意,我使用一個鍵輕松“分組”。

// 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()方法。

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

:)

使用doctrine DQL方法嘗試以下方法 -

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

而不是使用適當的包名替換AcmeDemoBundle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM