dongmo2324 2016-02-07 23:58
浏览 51
已采纳

Doctrine DQL连接表

for my API development I use apigility and doctrine. I'm currently programming an endpoint that users can like a post. Every post has an author. I have 2 tables with the following columns and example data inside:

Action

id  post_id   user_id  createdAt
1   10        1        0000-00-00 00:00:00
2   12        2        0000-00-00 00:00:00
3   13        3        0000-00-00 00:00:00

(post_id = foreign key to post table) (user_id = source user which likes a post)

Post

id  user_id   createdAt
10  62        0000-00-00 00:00:00
12  4         0000-00-00 00:00:00
13  4         0000-00-00 00:00:00

(user_id = foreign key to user table)

What I need

I need the total_likes which an author (user_id) has. This can be queried over the Action table by joining the post table. I have already tried to create a DQL query for this:

// Get total likes an autor has received
$queryBuilder->select('count(p)')
    ->from('Db\Entity\Action', 'a')
    ->leftJoin('p.post', 'p')
    ->where('p.user = :user')
    ->setParameter('user', $targetUser);
$totalLikes = $queryBuilder->getQuery()->getSingleScalarResult();

Which this query, I get the wrong number of total_likes:

{
  "total_likes": "2"
}

How do I have to correct this query that I get the correct count of likes of a user? With the example table data, the total_likes of user_id=62 should give me this back:

{
  "total_likes": "1"
}
  • 写回答

1条回答 默认 最新

  • doudou20080720 2016-02-08 01:34
    关注

    Try this:

    // Get total likes an autor has received
    $queryBuilder
        ->select('count(p)')
        ->from('Db\Entity\Action', 'a')
        ->leftJoin(
            'Db\Entity\Post',
            'p',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.post = p.id'
         )
         ->where('p.user = :user')
         ->setParameter('user', $users);
    
        $totalLikes = $queryBuilder->getQuery()->getSingleScalarResult();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题