CakeKP 3.x中的Subquerys,新的ORM?

时间:2016-06-12 15:19:45

标签: cakephp orm subquery cakephp-3.x

我是Cakephp 3.x的新手,我在使用新的ORM格式创建子查询时遇到了一些麻烦。我的申请表中有此报告,需要返回以下结果:
1.有三个实体 - 用户,呼叫,CallStatus 2.用户有多个电话,电话有多个CallStatus 3.我需要计算每个用户在Calls中有多少CallStatus 现在按照我需要放入新ORM格式的查询:

SELECT U.name,
    (SELECT COUNT(*) FROM calls as C WHERE C.call_status_id =1 and C.user_id=U.id) AS 'Unavailable',
    (SELECT COUNT(*) FROM calls as C WHERE C.call_status_id =2 and C.user_id=U.id) AS 'Busy',
    (SELECT COUNT(*) FROM calls as C WHERE C.call_status_id =3 and C.user_id=U.id) AS 'Contacted',
    (SELECT COUNT(*) FROM calls as C WHERE C.call_status_id =4 and C.user_id=U.id) AS 'Error'
FROM `users` AS U 
WHERE U.profile=3 and U.is_active=1

有人可以给我一个帮助吗?感谢

2 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望查看特定用户的每个callstatus的呼叫数。

尝试以下方法。请注意,我使用CakePHP约定来命名callstatuses(复数形式)。

// get the tableregistry  
use Cake\ORM\TableRegistry;
$callstatuses = Cake\ORM\TableRegistry::get('Callstatuses');

// for user with id 2, get the number of calls for each callstatus
$callstatuses->find()
    ->contain(['Calls'])
    ->where(['Calls.user_id' => 2, 'User.is_active' => 1])
    ->countBy('name')
    ->toArray();

// output could be:
//[ 'Unavailable' => 2, 'Busy' => 1 ]

您可以在CakePHP手册中找到有关创建查询的信息:请参阅'Query Builder'.

如果您想了解有关使用/查询查询的更多信息,请注意查询是集合。您可以在Collection对象上执行的任何操作,也可以在Query对象中执行。请参阅Collection section in the CakePHP book

答案 1 :(得分:0)

您必须使用子查询,尽可能多的! 以下是您的案例示例:

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


$q1->select([$q->func()->count('*')])
      ->where(['Calls.user_id = Users.id', 'call_status_id' => 1]);

$q2->select([$q->func()->count('*')])
      ->where(['Calls.user_id = Users.id', 'call_status_id' => 2]);

$q3->select([$q->func()->count('*')])
      ->where(['Calls.user_id = Users.id', 'call_status_id' => 3]);

$q4->select([$q->func()->count('*')])
      ->where(['Calls.user_id = Users.id', 'call_status_id' => 4]);

$qUsers = $this->Users->find()
         ->select([
              'id',  
              'first_name',  
              'Unavailable' => $q1,
              'Busy' => $q2,
              'Contacted' => $q3,
              'Error' => $q4
         ])
         ->where(['profile' => 3, 'active' => 1])
         ->all();

注意:如果在这种情况下使用循环创建suqueries,那就更好了。