简体   繁体   English

Dctrine DQL连接表

[英]Doctrine DQL join tables

for my API development I use apigility and doctrine . 对于我的API开发,我使用功能性和学说 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: 我有2个表,其中包含以下列和示例数据:

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 =喜欢发布的源用户)

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) (user_id =用户表的外键)

What I need 我需要的

I need the total_likes which an author (user_id) has. 我需要作者(user_id)拥有的total_likes。 This can be queried over the Action table by joining the post table. 可以通过加入post表在Action表中查询。 I have already tried to create a DQL query for this: 我已经尝试为此创建一个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();

Which this query, I get the wrong number of total_likes: 在此查询中,我得到了错误的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: 使用示例表数据,user_id = 62的total_likes应该给我以下信息:

{
  "total_likes": "1"
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM