【问题标题】:How can you count matches from a join action in CakePHP?如何计算 CakePHP 中连接动作的匹配数?
【发布时间】:2013-08-11 11:11:13
【问题描述】:

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

【问题讨论】:

    标签: php mysql cakephp join


    【解决方案1】:

    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);
    

    【讨论】:

      【解决方案2】:

      mysql应该是这样的:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-23
        • 2020-11-07
        • 1970-01-01
        相关资源
        最近更新 更多