2016-11-11 43 views
0

我怎么能转换MySQL查询:子查询在CakePHP 3.0

SELECT * , (

SELECT COUNT(*) 
FROM articles 
WHERE `user_id` =1 
) AS total_count 
FROM articles 
WHERE `user_id` =1 
GROUP BY user_id 

到CakePHP的子查询?

我已经试过了,

$articlescount = $this->Articles->find('all')->where(['user_id' => 1])->count(); 
print_r($articlescount); 

其中仅返回我没有计数。

回答

1

我怀疑你正在使用的查询是做你想要什么实现的,因为它似乎是查询和子查询都返回相同的值

反正这是你如何能得到的最好方式完全相同的查询,你问

$q = $this->Articles->find(); 

$q->select([$q->func()->count('*')]) 
    ->where(['user_id' => 1]); 

$q2 = $this->Users->find() 
    ->select(['total_count' => $q]) 
    ->autoFields(true) 
    ->where(['user_id' => 1]) 
    ->group(['user_id']) 
    ->all(); 

$q是子查询,而$q2是你想要的实际查询。

顺便说一句,我认为,你可以简单地做

$q = $this->Users->find() 
    ->select(['total_count' => $q->func()->count('*')]) 
    ->autoFields(true) 
    ->where(['user_id' => 1]) 
    ->group(['user_id']); 
0

Ariala的评论几乎是不错,但我认为这个代码更加灵活,因为suquery不包含用户ID固定的条件:

$q = $this->Articles->find(); 

$q->select([$q->func()->count('*')]) 
     ->where(['Articles.user_id = Users.id']); 

$q2 = $this->Users->find() 
     ->select(['id', 'first_name', 'total_count' => $q]) 
     ->where(['id' => 1]) 
     ->all(); 

但是如果你想列出所有用户的文章数量,你可以这样做,如果你离开$ q2的where条件。

它将结果是这样的:

id | first_name | total_count 
1 | John  | 3 
2 | Doe  | 0