0
votes

If I have a known set of users eg. by UID $users = {123, 435, 5463, 5678}. And I want to read the value stored in one custom field e.g. field_current_status that has been added to their user object is there any way to read this 1 value for each of them without loading their user objects.

I don't want to load up a lot of data for a lot of users just to get 1 value from each user.

I have looked at many functions including these below;

  • field_get_items($entity_type, $entity, $field_name, $langcode = NULL)
  • field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL)
  • field_view_value($entity_type, $entity, $field_name, $item, $display = array(), $langcode = NULL)
  • user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE)

These all require the the user object to be loaded e.g. with user_load($uid) or in effect do the same.

Is there any Drupal way to do this or must I write a custom DB query?

1

1 Answers

0
votes

The standard way to do this in Drupal would be to load the users with user_load_multiple($user_uids), this saves overhead in database queries by loading all objects at the same time. You can then just loop over the users and extract the required field:

$users = user_load_multiple($user_uids);
if (!$users) {
  return FALSE;
}

foreach ($users as $user) {
  $field_current_status = field_get_items('user', $user, 'field_current_status');
  if (!$field_current_status) {
    continue;
  }

  // Handle $field_current_status.
}

In terms of memory unless you were loading a massive number of users, you shouldn't really have a problem - Drupal itself has a high demand for memory. If memory is still a concern for you then you can use db_select() or db_query() to contruct a query to join the field_current_status table with the users table.

If this is a process that need to happen often then it may be worth looking into scheduling the cron to do it chunk by chunk.