2010-10-05 85 views
1

我在CakePHP中有一个虚拟字段,它需要是我的用户模型中三个完全不同的SQL查询的SUM。我试图通过拥有一个虚拟字段来实现这一点,该虚拟字段是3个其他虚拟字段的总和。CakePHP虚拟域是三个其他虚拟域的总和吗?

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中有没有办法做到这一点?

编辑

这里是蛋糕的生成的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

+0

生成的SQL看起来像什么? – deceze 2010-10-05 08:22:35

+0

@deceze编辑添加生成的SQL和确切的错误。 – 2010-10-05 09:54:19

回答

1

只需删除别名:在模型构造类似

'field_sum' => 'field_one + field_two + field_three' 
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); 
}