【问题标题】:Doctrine many to many: count left join collection多对多原则:count left join collection
【发布时间】:2023-04-09 18:07:02
【问题描述】:

注意:这是Doctrine many to many: has user liked the article?的后续跟进

拥有三个实体:用户、文章、评论以及用户和评论之间的“commentLikedByUser”多对多关系,我需要从文章中获取 cmets 集合,包括要使用的虚拟属性“userLiked”(布尔)在视图中。

//CommentRepository.php
public function findCommentsFromArticle($articleId,$userId)
{
    $result = $this->createQueryBuilder('c')
        ->where('c.article = :articleId')
        ->addSelect('COUNT(u) AS userLiked', 'c')
        ->leftJoin("c.users", 'u', 'WITH', 'u.id = :userId')
        ->setParameters(['articleId' => $articleId, 'userId' => $userId])
        ->orderBy('c.id', 'ASC')
        ->getQuery()
        ->getResult();

    dd($result);
}

这会转储以下内容:

如您所见,“userFavorite”不在正确的位置,而是在 Comment 对象之外。 我该如何解决这个问题?

【问题讨论】:

标签: php mysql symfony doctrine many-to-many


【解决方案1】:

也许试试这个代码:

//CommentRepository.php
public function findCommentsFromArticle($articleId,$userId)
{
   $result = $this->createQueryBuilder('c')
    ->where('c.article = :articleId')
    ->addSelect('COUNT(u) AS userLiked', 'c')
    ->leftJoin('c.users', 'u')
    ->andWhere('u.id = :userId')
    ->setParameters(['articleId' => $articleId, 'userId' => $userId])
    ->orderBy('c.id', 'ASC')
    ->getQuery()
    ->getResult();

dd($result);

}

【讨论】:

    【解决方案2】:

    我终于找到了使用 DQL 的解决方案。

    public function findCommentsFromArticle($articleId, $userId)
    {
        $em = $this->getEntityManager();
        $query = $em->createQuery("select c.id,c.text, count(u) as userFavorite
    from
    App\Entity\Comments c
    left join s.users u WITH u.id LIKE :userId 
    where c.article = :articleId
    group by c.id");
    
        $query->setParameters(['articleId' => $articleId, 'userId' => $userId]);
    
        return $query->getResult();
    }
    

    我必须手动选择列来附加虚拟属性“userFavorite”。否则它同样会在对象之外。

    希望这对某人有所帮助!

    【讨论】:

      猜你喜欢
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多