dousuie2222 2015-01-29 22:50
浏览 34
已采纳

OneToMany计数属性

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?

  • 写回答

1条回答 默认 最新

  • dongqiao8417 2015-01-29 23:22
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源