【问题标题】:Doing multiplication between 2 fields in CakePHP 2 find method在 CakePHP 2 查找方法中的 2 个字段之间进行乘法运算
【发布时间】:2015-04-03 12:44:03
【问题描述】:

我想在我的查找操作中计算 2 个字段的乘积,并在返回的数据中包含包含的答案。这两个字段属于 2 个相关模型。

2 模型:A 和 B。A 与 B 具有属于关系。

A 有字段“val1”,B 有字段“val2”。查找操作后,我想要存储在“A.prod”中的两个值的乘积。

我尝试过的:


$this->A->find('all', array('fields' => array('val1', 'B.val2', '(val1*B.val2) AS prod'))

这几乎可行,但将产品放在一个新数组中,而不是 A:

(int) 0 => array(
        (int) 0 => array(
            'prod' => '6'
        ),
        'A' => array(
            'val1' => '3'
        )
        'B' => array(
            'val2' => '2'
        )
    ),

也试过了:

$this->A->find('all', array('fields' => array('val1', 'B.val2', '(val1*B.val2) AS A.prod'))

但这会导致 MySQL 错误。


使用虚拟字段:

$this->A->virtualFields = array('prod' => 'A.val1*val2');
$this->B->virtualFields = array('val2' => 'B.val2');
$this->A->virtualFields += $this->B->virtualFields;
$this->A->find('all', array('fields' => array('prod', 'B.val2'))

这会产生错误“未找到列:1054 Unknown column 'val2' in 'field list'”

【问题讨论】:

    标签: cakephp cakephp-2.0


    【解决方案1】:

    这应该可行:

    $this->A->virtualFields = array('prod' => 'A.val1 * B.val2');
    $this->A->find('all', array('fields' => array('prod'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-14
      • 2016-08-17
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多