CakePHP:将计算字段从另一个模型连接到模型

时间:2012-10-28 02:24:17

标签: php mysql cakephp

我一直在试图弄清楚如何在CakePHP中为模型添加一些计算字段。我可以通过以下查询获得所需的结果:

SELECT project_id, 
    COUNT(*) AS clicks_total,
    SUM(CASE WHEN clicks.redirect_url = projects.url THEN 1 ELSE 0 END) AS clicks_redirected,
    SUM(CASE WHEN clicks.redirect_url = projects.url THEN 0 ELSE 1 END) AS clicks_not_redirected
FROM clicks
LEFT JOIN projects ON clicks.project_id = projects.id
GROUP BY project_id

如果我尝试将其作为自定义查询执行,那么Cake会以一种需要大量数组操作才能使用的方式转换结果。我尝试使用以下代码以Cake方式执行此操作,但由于某种原因,计算字段最终会出现在一个单独的数组中,这会导致视图中出现奇怪的行为:

$this->paginate = array(
'Project' => array(
    'fields' => array(
        'id', 'name', 'url', 'url_mac', 'url_mobile',
        'COUNT(*) AS clicks_total',
        'SUM(CASE WHEN Click.redirect_url = Project.url THEN 1 ELSE 0 END) AS clicks_redirected',
        'SUM(CASE WHEN Click.redirect_url = Project.url THEN 0 ELSE 1 END) AS clicks_not_redirected'

        ),
    'joins' => array(
        array(
            'table' => 'clicks',  
            'alias' => 'Click',  
            'type' => 'LEFT',
            'conditions' => array('Click.project_id = Project.id')  
        )
    ),
    'group' => 'project_id'
));

$this->set('projects', $this->paginate());

产生以下结果:

array(
    (int) 0 => array(
        'Project' => array(
            'id' => '508705c8-126c-48f9-bd9a-6d79d13bb9ea',
            'name' => 'Test Project',
            'url' => 'http://www.test.com',
            'url_mac' => 'http://www.mac.com',
            'url_mobile' => 'http://www.mobile.com'
        ),
        (int) 0 => array(
            'clicks_total' => '80',
            'clicks_redirected' => '35',
            'clicks_not_redirected' => '45'
        )
    ),
    (int) 1 => array(
        'Project' => array(
            'id' => '508b1073-2aa8-4895-b8d9-152ed13bb9ea',
            'name' => 'Another Project',
            'url' => 'http://another.com',
            'url_mac' => 'http://anothermac.com',
            'url_mobile' => 'http://anothermobile.com'
        ),
        (int) 0 => array(
            'clicks_total' => '134',
            'clicks_redirected' => '70',
            'clicks_not_redirected' => '64'
        )
    )
)

有没有人有任何想法让计算出的点击次数显示在Project数组下?

1 个答案:

答案 0 :(得分:1)

您可以向模型添加虚拟字段:

检查出来:http://book.cakephp.org/1.3/view/1608/Virtual-fields

  

在项目模型中:

     

public $ virtualFields = array('clicks_total'=>'COUNT(*)');