1

Is it important to use base table for entity in query? For example if I want to get all user's id of specific role, should I do:

  $query = db_select('users', 'u');
  $query->distinct();
  $query->fields('u', array('uid'));
  $query->innerJoin('users_roles', 'r', 'u.uid = r.uid');
  $query->condition('r.rid', 3);

or

  $query = db_select('users_roles', 'r');
  $query->fields('r', array('uid'));
  $query->condition('r.rid', 3);
5

No, it's not important, nor necessary.

There's no API method for getting this information, so going directly into the database is fair game. Once you're going directly into the database, you only need to include the tables and fields that your data requires - anything else is a waste of resources.

In this case, you don't need to select or filter anything from the users table, so there's no need to join it in (unless you're worried about referential integrity, and want to make sure the user record actually exists).

3

In your case, the second query is enough, unless you need additional filtering/conditions that depend on the base table (e.g. to select only active users).

Generally speaking, core base tables can have certain tags that give you additional processing/filtering out of the box. The best example is the node_access tag, which if you add to a query that runs against {node} table, will automatically perform node access checks, and fetch only the nodes currently active user has access to. This might be something to consider if you're querying node-related information.

You can read more about query alteration (tagging) here.

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.