2

Works:

$rows = db_select('notification_queue', 'nq')
    fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method','latest_time', 'earliest_time'))
    ->groupBy('uid')
    ->groupBy('notification_type')
    ->groupBy('delivery_method')
    ->addExpression('COUNT(*)', 'count')
    ->execute();

Does not work:

$rows = db_select('notification_queue', 'nq');
$rows->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'));
$rows->groupBy('uid');
$rows->groupBy('notification_type');
$rows->groupBy('delivery_method');
$rows->execute();

I'm testing that something is returned with a simple foreach loop:

foreach($rows as $row) {
    msg($row); //msg is a simple wrapper for drupal set message
}

The reason I need to do things the second way is that I have to use addExpression and it won't work if try and use it in the first way.

I've tried this:

$rows = db_select('notification_queue', 'nq');
$rows->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'));
$rows->groupBy('uid');
$rows->groupBy('notification_type');
$rows->groupBy('delivery_method');
$rows->addExpression('COUNT(*)', 'count');
$rows->execute();

And I've checked that the resulting query is correct (it is, I've tried using it with MySQL directly and it does exactly what I want). However, I can't get access to the rows using Drupal.

What am I doing wrong?

1 Answer 1

1

Turns out addExpression does not return the object, just the alias of the expression. Solution:

$query = db_select('notification_queue', 'nq')
    ->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'))        
    ->groupBy('uid')
    ->groupBy('notification_type')
    ->groupBy('delivery_method');

$query->addExpression('COUNT(*)', 'num');
$rows = $query->execute();
2
  • ...answering your own question? NOOB! Do you even know what DRUPAL stands for?
    – Coomie
    Commented Jan 31, 2013 at 8:29
  • $rows = $query->execute(); is the key there Commented Jan 31, 2013 at 11:05

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.