代码之家  ›  专栏  ›  技术社区  ›  Daniel Bingham

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

  •  1
  • Daniel Bingham  · 技术社区  · 15 年前

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

    这不管用。当到达“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 error:1054 unknown column User.field_one 在字段列表中。

    2 回复  |  直到 15 年前
        1
  •  1
  •   Toto    15 年前

    'field_sum' => 'field_one + field_two + field_three'
    
        2
  •  1
  •   Jamie    15 年前

    我在模型构造函数中也做过类似的事情,通过回收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);
    }