Search code examples
phpsymfonydoctrinedql

OneToMany count attribute


I have two entities, post and like, post has a OneToMany to like.

Post Class

   /**
 * Post
 *
 * @ORM\Table()
     * @ORM\Entity(repositoryClass="Mag\MyBundle\Entity\PostRepository")
     */
    class Post {
//...

/**
 *@ORM\OneToMany(targetEntity="Mag\MyBundle\Entity\LikePost",mappedBy="post")
 *
 */
private $likes;
private $countLikes; 

//...
}

Like Class

/**
 * LikePost
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class LikePost
{
//...

  /**
     * @ORM\ManyToOne(targetEntity="Mag\MyBundle\Entity\Post",cascade={"persist"},inversedBy="likes")
     * @ORM\JoinColumn(nullable=false)
     */
    private $post ;
    //...
}

I want to get the count of likes in posts. i tried in the PostRepository

$qb = $this->createQueryBuilder('p');
       $query = $qb
                ->addSelect($qb->expr()->count('l'))
                ->leftJoin('p.likes', 'l')
                ->groupBy('p.id')
                ->orderBy('p.datePost', 'DESC')
                ->setFirstResult(($page - 1) * $count)
                ->setMaxResults($count)
                ->getQuery();

but it give an array of the two selection query. How can i store the result of "->addSelect($qb->expr()->count('l'))" in the "$countLikes" attribute in post object?


Solution

  • You might be able to write custom hydration driver which interprets the results but I haven't done anything like that yet.

    Can you do it manually?

    $query = $qb
        ->addSelect($qb->expr()->count('l'))
        ->leftJoin('p.likes', 'l')
        ->groupBy('p.id')
        ->orderBy('p.datePost', 'DESC')
        ->setFirstResult(($page - 1) * $count)
        ->setMaxResults($count)
        ->getQuery();
    
    $result = $query->getResult();
    $actualResult = array();
    
    foreach ( $result as $r ){
        // assuming that object is at position `0` and like count at position `1`
        $r[0]->setCountLikes(intval($r[1]));
    
        $actualResult[] = $r[0];
    }
    
    return $actualResult;