Furqan
Furqan

Reputation: 1

Cakephp 3 Sum 2 columns of same table

How to Sum two columns of the same table in CakePhp 3 ? lets say i want to sum the values of two columns i.e stitching_amount and item_amount of table order_details .. So how can I do this ?

I have tried this piece of code for this but it is not working in Cakephp 3.8 ..

$query = $this->OrderDetails->find();
$query
    ->select([
        'val' => $query
            ->newExpr()
            ->add($query->func()->sum(
                new IdentifierExpression('OrderDetails.item_amount')
            ))
            ->add($query->func()->sum(
                new IdentifierExpression('OrderDetails.stitching_amount')
            ))
            ->tieWith('+')
    ])
    ->where(['order_id' => $lastorderid]);

Whereas I have done this in corephp and its working perfectly, I want to do this in Cakephp3, like this

SELECT
    SUM(stitching_amount+item_amount) AS Total
FROM
    order_details
WHERE
    id=" . $run_orders['id'];

Upvotes: 0

Views: 123

Answers (1)

segy
segy

Reputation: 162

Try this:

$query->select([
    'Total' => $query->func()->sum($query->newExpr('OrderDetails.item_amount + OrderDetails.stitching_amount'))
]);

Upvotes: 1

Related Questions