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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c