Doctrine DQL连接表

时间:2016-02-07 23:58:33

标签: php sql doctrine-orm doctrine apigility

对于我的API开发,我使用apigility和 doctrine 。我目前正在编写一个用户可以喜欢帖子的端点。每个帖子都有一个作者。我有2个表,其中包含以下列和示例数据:

动作

for (long key = 0; key < 5; key++)
{
    var localKey = key;
    var processingThread = new Thread(() => Setup(localKey));
    processingThread.Start();
}

(post_id =发布表的外键) (user_id =喜欢帖子的源用户)

发表

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

(user_id =用户表的外键)

我需要什么

我需要作者(user_id)拥有的total_likes。可以通过加入post表在Action表上查询。我已经尝试为此创建一个DQL查询:

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

这个查询,我得到的错误数量为total_likes:

// 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();

如何更正此查询以获得用户喜欢的正确数量?使用示例表数据,user_id = 62的total_likes应该给我回复:

{
  "total_likes": "2"
}

1 个答案:

答案 0 :(得分:1)

试试这个:

// 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();
}