【发布时间】:2016-02-07 23:58:33
【问题描述】:
对于我的 API 开发,我使用 apigility 和 doctrine。我目前正在编写一个用户可以喜欢帖子的端点。每个帖子都有一个作者。我有 2 个表,其中包含以下列和示例数据:
动作
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 = 发布表的外键) (user_id = 喜欢帖子的源用户)
发帖
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 = 用户表的外键)
我需要什么
我需要作者(user_id)拥有的total_likes。这可以通过加入 post 表对 Action 表进行查询。我已经尝试为此创建一个 DQL 查询:
// 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();
这个查询,我得到了错误的total_likes数:
{
"total_likes": "2"
}
我必须如何更正此查询才能获得正确的用户点赞数?使用示例表数据,user_id=62 的 total_likes 应该会返回给我:
{
"total_likes": "1"
}
【问题讨论】:
标签: php sql doctrine-orm doctrine laminas-api-tools