如何在CakePHP中计算join操作的匹配数?

nzk0hqpo  于 2022-11-12  发布在  PHP
关注(0)|答案(2)|浏览(162)

我想计算一个额外创建的字段,从一个连接的匹配。这在CakePHP中是可能的吗?我有一个我的数据的例子,我现在有。
对于这种类型的结果,mySQL中的查询是什么样子的?
表:目标

id | name 
-----------
1    Goal X
2    Goal Y

表:任务

id | name | goal_id
-------------------
1    task1  1
2    task2  1
3    task3  2
4    task4  2
5    task5  2

测试结果

id | name | matches
-------------------
1    goal1  2
2    goal2  3
wgxvkvu9

wgxvkvu91#

MySQL查询:

SELECT goal.id, goal.name, Count( * ) AS matches
FROM goal
RIGHT JOIN task ON goal.id = task.goal_id
GROUP BY goal.id

CakePHP:[如果你有一个名为Goal and Task的模型]

$options['fields'] = array(
                           'Goal.id', 
                           'Goal.name', 
                           'count(*) AS matches'
                   );
$options['joins'] = array(
                              array(
                                 'table' => 'tasks',
                                 'alias' => 'Task',
                                 'type' => 'Right',
                                 'conditions' => array(
                                    'Goal.id = Task.goal_id'
                                 )
                              ) 
                    );
$options['group'] = array('Goal.id');

$result = $this->Goal->find('all', $options);
2nbm6dog

2nbm6dog2#

mysql应该是:

Select goal.id,goal.name,Count(*) From goal RIGHT JOIN tasks on goal.id=tasks.goal_id Group by goal.id

CakePHP,不能告诉你没有测试...

相关问题