3

I want the date for the last login for a defined role, but I have a problem with my query with drupal 7.

I have the good answer in phpmyadmin with this query :

SELECT login FROM `users` AS u, `users_roles` AS r
WHERE u.uid = r.uid
AND r.rid = 3
ORDER BY login DESC LIMIT 1

But an error with Drupal7... I tried this code :s :

$query = db_select('users','u')
 ->join('users_roles','r','r.uid = u.uid')
 ->fields('u',array('uid'))
 ->fields('r',array('rid'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'DESC')
 ->range(0,1);
$res = $query->execute();

Thanks

Edit : Thank for your answer Clive , this code works :

$query = db_select('users','u');
$query->join('users_roles','r','r.uid = u.uid');
$query->fields('u',array('login'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'ASC')
 ->range(0,1);

$res = $query->execute();      
return $res->fetchField();
2

SelectQuery::join() returns the alias created, not the query object, so it can't be chained. This should work

$query = db_select('users','u')
 ->fields('u',array('uid'))
 ->fields('r',array('rid'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'DESC')
 ->range(0,1);

$query->join('users_roles','r','r.uid = u.uid');
$res = $query->execute();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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