-1

我一直在试图弄清楚如何在 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 数组下?

4

1 回答 1

1

您可以将虚拟字段添加到模型中:

看看:http ://book.cakephp.org/1.3/view/1608/Virtual-fields

在项目模型中:

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

于 2012-10-28T21:56:01.213 回答