Q:

How to sort by a fields content?

so I have a content-type called "Team Member" and I'd like to sort for the field "last_name".
I currently get all the nodes using:
nids = db_select('node', 'n')
->fields('n', array('nid', 'field_last_name'))
->condition('type', 'team_member')
->orderBy('n.title','ASC')
->execute()
->fetchCol();

So currently, they are sorted using the title. How can I now tell it to sort using "last_name" field? I just don't see what exactly db_select needs to know here.
Im on D7.

A:

You shouldn't query the database directly for entity data, there are APIs for that.
In this case you need an EntityFieldQuery:
$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'team_member')
  ->propertyCondition('status', 1)
  ->fieldOrderBy('field_last_name', 'value');

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
}

