PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 10, 2022

[FIXED] CakePHP 3 : how to make a sum of 2 columns

 March 10, 2022     cakephp, cakephp-3.0, expression, query-builder, sql     No comments   

Issue

I have a problem with a sql request, I want to sum 2 columns : This syntax do not works ...

$query=$this->Results->find()
    ->contain(['Users', 'Events'])
    ->select([
        'user_id'=>'Users.id',
   'val'=>$query->func()->sum('Events.value')+$query->func()->sum('Results.value')
    ])
    ->group(['user_id']); 

I expect something like that in the sql request :

SUM(Events.value)+SUM(Results.value)) AS `val 

How can I do that with cake ?

Thanks


Solution

What you're doing there is adding two objects on PHP level, that will cause the objects to be casted to integers, which surely won't work and fail with an error.

You need to use the expression builder to build an expression that produces the desired SQL, just add your function expressions and tie/conjugate them with the + operator. Also you cannot access $query before it has been defined, and I'd suggest to use identifier expressions for the colum names that you're passing to sum():

use Cake\Database\Expression\IdentifierExpression;

// ...

$query = $this->Results->find();
$query
    ->contain(['Users', 'Events'])
    ->select([
        'user_id' => 'Users.id',
        'val' => $query
            ->newExpr()
            ->add($query->func()->sum(new IdentifierExpression('Events.value')))
            ->add($query->func()->sum(new IdentifierExpression('Results.value')))
            ->tieWith('+') // setConjunction() as of CakePHP 3.4
    ])
    ->group(['user_id']);

See also

  • API > \Cake\Database\Expression\QueryExpression


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing