首页 > 解决方案 > 使用 MySQL 用户定义变量和 CakePHP3 查询选择

问题描述

这是我需要的一个例子:

SELECT 
    @earnings := (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) AS earnings ,
    @deductions := (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`) AS deductions,
    @earnings - @deductions AS net_salary 
FROM 
    salary

就我而言,我需要将 aSUM(Table.total)作为单独的salesTotal列返回,并在内部重用@salesTotal/@salesQuantity.

这是我尝试过的:

1.

$query->select([
    $query->newExpr([
        '@salesTotal := ',
        $query->func()->sum('Table.total')
    ]),
]);

这会产生@salesTotal := AND SUM(Table.total)

2.

$query->select([
    $query->newExpr([
        '@salesTotal := ' . $query->func()->sum('Table.total')
    ]),
]);

导致警告 (4096):Cake\Database\Expression\FunctionExpression 类的对象无法转换为字符串

3.

$query->select([
    $query->newExpr([
        '@salesTotal := SUM(Table.total)'
    ]),
]);

收到警告 (2): array_combine () : 两个参数应该有相同数量的元素CORE/src/ORM/ResultSet.php,第 527 行。这也不是一个好的解决方案

标签: mysqlcakephpcakephp-3.0

解决方案


由于您没有绑定任何值,因此您可以简单地按字面意思编写子句,而无需任何复杂性。像这样:

$query
    ->select(array(
        '@earnings := (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) AS earnings',
        '@deductions := (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`) AS deductions',
        '@earnings - @deductions AS net_salary',
    ))
    ->from('salary')
;

我没有一个填充表来测试它并确定它确实返回了你想要的,但它确实使用 CakePHP 为这个结构返回了一个空数组(而不是抛出异常):

CREATE TABLE salary (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    house_rent INT DEFAULT 0,
    conveyance INT DEFAULT 0,
    medical INT DEFAULT 0,
    dearness INT DEFAULT 0,
    others_allowances INT DEFAULT 0,
    income_tax INT DEFAULT 0,
    pro_tax INT DEFAULT 0,
    emp_state_insu INT DEFAULT 0,
    absence_fine INT DEFAULT 0,
    others_deductions INT DEFAULT 0
);

推荐阅读