Score:0

Database addExpression SUM: Call to a member function execute() on string

at flag

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

Score:3
de flag

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();
Ricardo Castañeda avatar
at flag
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)
Jaypan avatar
de flag
`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.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.