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

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题