Search code examples
phpsymfonydoctrine-ormdoctrinedql

Combine two different DQL


I am trying to modify a DQL to combine two different results:

class ContentRepository extends EntityRepository
{
    /**
     * @param string $userId
     * @return array
     */
    public function findOwnerReadByUserId(string $userId): array
    {
        $qb = $this->createQueryBuilder('c');
        $qb->select('c')
            ->innerJoin('c.reactions', 'rea', Join::WITH, $qb->expr()->eq('rea.content', 'c.id'))
            ->where('c.userId = :userId')
            ->orderBy('rea.createdAt', 'DESC')
            ->setParameters(['userId' => $userId]);

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

    /**
     * @param string $userId
     * @return array
     */
    public function findOtherReadByUserId(string $userId): array
    {
        $qb = $this->createQueryBuilder('c');
        $qb->select('c')
            ->innerJoin('c.receivers', 'rec', Join::WITH, $qb->expr()->eq('rec.userId', ':userId'))
            ->innerJoin('c.reactions', 'rea', Join::WITH, $qb->expr()->eq('rea.content', 'c.id'))
            ->where('rec.read = :read')
            ->orderBy('rea.createdAt', 'DESC')
            ->setParameters(['userId' => $userId, 'read' => true]);

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

Both queries are working like a charm but I would like to avoid the array_merge because of the order by. Any suggestion to retrieve both results in one single DQL?

SQLfiddle Link


Solution

  • Thanks to @AlexBlex

    this is the answer:

        /**
         * @param string $userId
         * @return array
         */
        public function findNotPendingByUserId(string $userId): array
        {
            $dql = <<<DQL
      SELECT DISTINCT c
      FROM ApiBundle:Content c
      INNER JOIN c.receivers rec 
      INNER JOIN c.reactions rea
      WHERE (rec.read = true AND (c.userId = :userId OR rec.userId = :userId))
      ORDER BY rea.createdAt DESC
    DQL;
    
            return $this->getEntityManager()
                ->createQuery($dql)
                ->setParameters(['userId' => $userId])
                ->getResult();
        }