1

friends! I want to get the selected columns of my object from the database, as well as the selected columns of the related objects. But when I execute my query, I get the data but the related objects are not converted into separate arrays but are returned in the general array of the main requested object.

My query:

$query = $this->createQueryBuilder('i')
        ->select('i.id', 'i.payStatus', 'contract.id as contract_id', 'contract.type as type')
        ->join('i.contract', 'contract');
    return $query->getQuery()->getResult();

Current result:

{
  "id": 56,
  "payStatus": 2,
  "contract_id": 5,
  "type": 2
}

Expected Result:

{
  "id": 56,
  "payStatus": 2,
  "contract": {
      "contract_id": 5,
      "type": 2
  }
}

I would be grateful for any help!

  • 1
    I'm not sure if this is possible out of the box. Doctrine always fetches the data as a flat array using your entity mapping (e.g. via Annotations) to map the data to your nested structure. If you don't map the data to your entity then Doctrine is not able to see how the data should be nested. You could write a custom Hydrator or just map the data manually from the result. – dbrumann Apr 02 '21 at 06:32
  • Hello dbrumann. Thank you very much for your answer. I mark it as correct, so in fact it is not possible to implement what I described from under the box. Leave your answer and I will mark it as correct. thanks – Kirill Buziuk Apr 02 '21 at 16:57

1 Answers1

1

When you select multiple scalar fields, doctrine always returns flat array with all the "columns".

There are two options I see:

  • you can save $query->getQuery()->getResult() in your query method, map it yourself and return the mapped results.
  • if you want to map it to some entities, you can use "native queries" and "result set mapping", then you have can have nested objects in the result while having full control over the mapping. https://www.doctrine-project.org/projects/doctrine-orm/en/2.8/reference/native-sql.html However in the idiomatic doctrine way, you should avoid native queries when possible.
Matěj Koubík
  • 1,087
  • 1
  • 9
  • 25
  • Hello. Yes, you are right, thank you. This is exactly what dbrumann wrote earlier in the comments to the question, thanks for your answer, it is also correct. – Kirill Buziuk Apr 02 '21 at 16:59