2

I work with:

$mandator = $this->database->select('Mandators', 'm')
     ->fields('m')
     ->condition('idMandators', $mandatorId)
     ->execute()
     ->fetchAll();

to retrieve my data from database. The result is an array with 1 array item. How can I retrieve always only 1 object, without the array? Like e.g. ->fetchOne?

4 Answers 4

2
$query = \Drupal::entityQuery('node')
            ->condition('status', 1)
            ->condition('type', 'my_content_type')
            ->condition('field_ref_au', $nid, '=')
            ->range(0,1)
            ->sort('created', 'DESC')
        ;
0

This works

$database = \Drupal::database();
$row = $database->query("SELECT column_name FROM {table_name} WHERE column_required = :value", [':value' => $value]);
-2

As per my understanding I would say try to count the number of rows like this:

$number_of_rows = db_select('node')->countQuery()->execute()->fetchField();

then iterate to get the first count.

Or:

// Get a single record out of the database.
$node = db_query("SELECT * FROM {node} WHERE nid = :nid", array(':nid' => $nid))->fetchObject();
-4

You can simply write (example get node) :)

$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n)->fetchObject();

If you want to get a single value you can use fetchField()

Example (get node title):

$node_title = db_query('SELECT title FROM {node} WHERE nid = :nid', 
array(':nid' => $nid))->fetchField();
1
  • Thanks for your quick answers. db_query() is deprecated/very old. I prefer the database object. I am wondering, why the query methods are lacking documentation on drupal.org. We should probably add some. Even you could try them or use the evaluate expression function in phpstorm ide. Probably ->fetchField() and fetchObject() can be adapted to the database object.
    – jepster
    Commented Nov 14, 2017 at 22:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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