Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

QueryBuilder results not grouping in array

Hello all,

Why is this:

$surcharges = $this->modelsManager->createBuilder()
    ->columns(['surcharge.*', 'company.*', 'match.*'])
    ->addFrom('Tariff\\Surcharge', 'surcharge')
    ->leftJoin('\\Company', 'surcharge.company_id = company.id', 'company')
    ->leftJoin('Tariff\\SurchargeMatch', 'surcharge.tariff_surcharge_match_id = match.id', 'match')
    ->where(join(' AND ', $where), $bind)
    ->limit($limit, $start)
    ->getQuery()
    ->execute();

echo json_encode($surcharges->toArray());

returning this:

[{
    "surcharge": {
        "id": "407b3096-e706-1a2f-a0b4-67e4a4d0eb14",
        "name": "Cash-on-delivery",
        "company_id": null,
        ...
    },
    "company": {
        "id": null,
        "account_no": null,
        "pickup_address_no": null,
        "name": null,
        ...
    },
    "match": {
        "id": "5c9c20c0-9ed2-ee5d-ebd4-b45e14a0b3e0",
        "name": "Cash-on-delivery",
        "code": "B",
        "text": "",
        ...
    }
}]

However, when I use single columns:

->columns(['surcharge.*', 'company.name', 'company.id', 'match.code', 'match.text', 'match.id'])

It doesn't group the table results:

  [{
      "surcharge": {
      "id": "407b3096-e706-1a2f-a0b4-67e4a4d0eb14",
      "name": "Cash-on-delivery",
      "company_id": null,
      "country_code": "NL",
      "amount": 20,
      "percent": 0,
      "description": "",
      ...
      },
      "name": null,
      "id": "5c9c20c0-9ed2-ee5d-ebd4-b45e14a0b3e0",
      "code": "B",
      "text": ""
  }]

I think this is unwanted behavior, or is there some argument that I'm missing?

Greets, Tim



38.6k
Accepted
answer

This is the intended behaviour. When using the * selector, result sets are collection of objects (models), not just simple arrays. Only when you excplicitly define columns do you get arrays. (as you've shown)

This way you can use each item as if returned from find / findFirst, which is logical in an MVC pattern.

https://docs.phalconphp.com/en/latest/reference/models.html#hydration-modes