CakePHP虚拟字段是三个其他虚拟字段的总和?

时间:2010-10-05 07:32:53

标签: php mysql cakephp

我在CakePHP中有一个虚拟字段,需要在我的用户模型中包含三个非常不同的SQL查询的SUM。我试图通过一个虚拟字段来实现这一点,虚拟字段是3个其他虚拟字段的总和。

var $virtualFields = array (
        'field_one' => 'select coalesce(sum(coalesce(t_a.field, 0)), 0)*10 as field_one from t_a join t_b on t_a.t_b_id = t_b.id where t_b.user_id=User.id',
        'field_two' =>  'select coalesce(sum(coalesce(t_c.field, 0)), 0)*2 as field_two from t_d left join (t_c) on (t_d.id=t_c.t_d_id) where t_d.user_id = User.id',
        'field_three' => 'select coalesce(sum(coalesce(value, 0)), 0) as field_three from t_e where user_id=User.id',
        'field_sum' => 'User.field_one+User.field_two+User.field_three'
    );

这不起作用。当它到达'field_sum'时,我得到错误'field_one不存在'。我之前已经问过如何结合三个sql语句并没有真正得到满意的答案。事实证明,单独运行它们并在事后总结它们会更好更容易。在CakePHP的上下文中有没有办法做到这一点?

修改

这是cake生成的SQL:

SELECT 
    /* Users fields */
    (select coalesce(sum(coalesce(t_a.field, 0)), 0)*10 as field_one from t_a join t_b on t_a.t_b_id = t_b.id where t_b.user_id=User.id) AS `User__field_one`, 
    (select coalesce(sum(coalesce(t_c.field, 0)), 0)*2 as field_two from t_d left join (t_c) on (t_d.id=t_c.t_d_id) where t_d.user_id = User.id) AS  `User__field_two`, 
    (select coalesce(sum(coalesce(value, 0)), 0) as bonus_reputation from reputation_bonuses where user_id=User.id) AS  `User__field_three`,        (`User`.`field_one`+`User`.`field_two`+`User`.`field_three`) AS  `field_sum`, 
    FROM `users` AS `User`   
    WHERE `User`.`email` = '/* redacted */' AND `User`.`password` = '/* redacted */'    LIMIT 1 

看到我尝试将定义更改为(User__field_one+User__field_two+User__field_three)以利用它们的命名方式。没有运气。

确切的错误是:SQL错误:字段列表中的1054未知列User.field_one

2 个答案:

答案 0 :(得分:1)

只需删除别名:

'field_sum' => 'field_one + field_two + field_three'

答案 1 :(得分:1)

我在模型构造函数中做了类似的事情,通过回收SQL片段。不是最有效的,但它可能会奏效。类似的东西:

function __construct($id = false, $table = null, $ds = null) {
    $snippet1 = 'select coalesce(sum(coalesce(t_a.field, 0)), 0)*10 as field_one from t_a join t_b on t_a.t_b_id = t_b.id where t_b.user_id=User.id';
    $snippet2 = 'select coalesce(sum(coalesce(t_c.field, 0)), 0)*2 as field_two from t_d left join (t_c) on (t_d.id=t_c.t_d_id) where t_d.user_id = User.id';
    $snippet3 = 'select coalesce(sum(coalesce(value, 0)), 0) as field_three from t_e where user_id=User.id';

    $this->virtualFields['field_one'] = $snippet1;
    $this->virtualFields['field_two'] = $snippet2;
    $this->virtualFields['field_three'] = $snippet3;

    $this->virtualFields['field_sum'] = $snippet1.' + '.$snippet2.' + '.$snippet3;

    parent::__construct($id, $table, $ds);
}