3

我想计算一个创建的额外字段,即来自连接的匹配项。这在 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
4

2 回答 2

4

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 : [如果您有名称为目标和任务的模型]

$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);
于 2013-08-09T14:13:56.633 回答
0

mysql应该是这样的:

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

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

于 2013-08-09T13:45:54.303 回答