2

I have a very simple query that does the job, to get a collection of a specific content type's node id and title, that's it.

$connection = \Drupal::database();
$query = $connection->select('node_field_data', 'n');
$query->condition('n.type', 'employee');
$query->condition('n.status', 1);
$query->fields('n', ['nid', 'title']);
$results = $query->execute()->fetchAll();

And what i get is an array filled with objects (for each individual results) with two properties the nid and title values. But i want to have an single layer/dimension array filled with key => valued pairs (nid => title). Example bellow.

$results = [
  0 = {stdClass} (
     nid => 123,
     value => Susan Green
  )
];

And what i want:

$results = [
  123 => Susan Green,
  567 => Bob Young
];

I've tried fetchAllAssoc, fetchAssoc, etc but either the result is empty or i get something completely opposite of what i want.

Any ideas? without using a parses to convert objects into what i want, that's what i'll do if none one can find an appropriate answer.

3

You can use fetchAllKeyed try with:

  $connection = \Drupal::database();
    $query = $connection->select('node_field_data', 'n');
    $query->condition('n.type', 'employee');
    $query->condition('n.status', 1);
    $query->fields('n', ['nid', 'title']);
    // use fetchAllKeyed
    $results = $query->execute()->fetchAllKeyed(0,1);
  • Gives this person a cookie, you are correct, thank you! – lordZ3d Jan 17 at 8:15
  • you are welcome, i'm glad that help :) – berramou Jan 17 at 8:49

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.