0

I need to get the sum of all points values of the user with uid 1 from the test_sum_expression table. But when I try to execute I get this message Error: Call to a member function execute() on string.

If I don't execute, I get the count 6 of the word points, as if it were counting the characters from the string points.
enter image description here

$queryPoints = $connection->select('test_sum_expression', 'n')
    ->fields('n', ['uid', 'points'])
    ->condition('n.uid', 1, '=')
    ->groupBy('n.uid')
    ->addExpression('SUM(n.points)', 'points')
    ->execute();


dpm($queryPoints);

Mysql table with two columns (uid, points)

enter image description here

1 Answer 1

3

This is because addExpression() returns the unique alias assigned to the expression, and not the query. You can fix this by adjusting your code as follows:

$query = $connection->select('test_sum_expression', 'n')
    ->fields('n', ['uid', 'points'])
    ->condition('n.uid', 1, '=')
    ->groupBy('n.uid');
$query->addExpression('COUNT(n.points)', 'points');
$queryPoints = $query->execute();
2
  • Thanks for your answer. But by mistake in the question I wrote the code with COUNT instead of SUM. My apologies. I've corrected the question. Does this code work with SUM? I'm getting with dpm($queryPoints): $queryPoints Drupal\Core\Database\StatementWrapper#458455 (3) Jul 10, 2023 at 21:15
  • 2
    addExpression() returns a string, whether you pass it SUM or COUNT, so my code is the same either way. Whether that code does what you are hoping is a different question - I am helping with the syntax only.
    – Jaypan
    Jul 10, 2023 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.