TransWikia.com

How to sort the query results?

Drupal Answers Asked by badm on October 26, 2021

In my task I need to display the results based on “the newest first”. I perform a query:

$query = Drupal::database()->select('node_field_data', 'node');
$query->innerJoin('node__field_ils_apps', 'app', 'app.entity_id = node.nid AND app.field_ils_apps_target_id = '.$node->id());
$query->addField('app', 'entity_id', 'nid');
$query->groupBy('app.entity_id');

$query->orderBy('created', 'DESC');
$query->execute();

But it returns me an error:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 

Could you please tell me what I do wrong?

One Answer

Try this out

use DrupalCoreDatabaseDatabase;

$connection = Database::getConnection();
  //- Step one get all referenced nids
  $query = $connection->select('node_field_data', 'nfd')
    ->fields('nfd', ['nid', 'created']);
   $query->innerJoin('node__field_ils_apps', 'app', 'nfd.nid = app.entity_id');
  $query->orderBy('created', 'DESC');
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

Answered by berramou on October 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP