I rewrote for Drupal 8 a Drupal 6 query on 3 custom entities (see here):

$database = \Drupal::database();
$query = $database->select('amap_distributions_dates', 'amdd');
$query->leftJoin('amap_distributions_inscriptions', 'amdi', 'amdi.datedistributionid = amdd.id');
$query->leftJoin('association_personne', 'ap', 'ap.id = amdi.amapienid');
$query->fields('amdd', ['id', 'datedistribution', 'nombreproduits'])
    ->fields('amdi', ['id', 'datedistributionid', 'amapienid', 'role'])
    ->fields('ap', ['id', 'nom', 'prenom'])
    ->condition('nombreproduits', 0, '>')
    ->orderBy('datedistribution', 'ASC')
    ->orderBy('role', 'ASC')
    ->orderBy('nom', 'ASC')
    ->orderBy('prenom', 'ASC');
$results = $query->execute()->fetchAllAssoc('id');
foreach ($results as $row) { some code here }

Unfortunately, I can retrieve only the last of each {datedistribution-role-nom}.
For each 'datedistribution', if I have more than one 'role' or 'name', I can get only the last one considering the sort order I put in place.
Strange, no?
Any idea why?

  • 2
    Don't use fetchAllAssoc(). Just $result = $query->execute() and then loop over that.
    – Berdir
    Commented Jul 2, 2016 at 8:59
  • You should consider loading the entire entity objects using entityQuery and loadMultiple.
    – Eyal
    Commented Jul 3, 2016 at 16:24
  • @Berdir Do you know why I can't accept your comment as an 'answer' to my question?
    – gbmapo
    Commented Jul 4, 2016 at 10:17

1 Answer 1


Don't use fetchAllAssoc(). Just $result = $query->execute() and then loop over that


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.