2010-10-05 80 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); 
}