2016-02-07 90 views
0

爲我的API開發我使用apigility和教條。我目前正在編寫一個用戶可以喜歡的帖子。每篇文章都有一位作者。我有2個表有以下的列和實例數據內:Doctrine DQL加入表

行動

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。這可以通過加入郵件表來查詢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" 
} 

回答

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

謝謝,你真棒!完美工作:-) –