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

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'
    );

这不管用。当它到达“FieldIn和”时,我得到了错误“FieldIn一个不存在”。我以前问过如何组合这三个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 error:1054字段列表中的未知列User.field_one

最佳答案

只需删除别名:

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

10-08 08:00
查看更多