fetching result from database in specific format cakephp5

I am currently in the process of migrating from CakePHP 2.8 to CakePHP 5.x. In CakePHP 2.8, I used to retrieve results in the following format:

$this->find('all', array(
    'contain' => array('UserDetail'),
));

Array
(
    [ModelName] => Array
        (
            [id] => 83
            [field1] => value1
            [field2] => value2
            [field3] => value3
        )
        
    [UserDetail] => Array
       (
            [id] => 1
            [field1] => value1
            [field2] => value2
            [field3] => value3
       )
)

However, after migrating to CakePHP 5.0, the results are now in the following format:

    (
    (
        [id] => 83
        [field1] => value1
        [field2] => value2
        [field3] => value3
        [user_detail] => Array
        (
            [id] => 1
            [field1] => value1
            [field2] => value2
            [field3] => value3
        )
    )
)

$query  = $this->find('all')->contain(['UserDetail']);
$result = $query->toArray();

Is there a way to retrieve the results in CakePHP 5.x in the same format as in CakePHP 2.8?

Thank you for any assistance in this CakePHP 5.x migration from 2.x.

Take a look at the Collection class. I would probably use Collection::reduce(); it’s one of my go-to tools.

You can also integrate the data structure transformation into the query (still using Collection tools) using the Map/Reduce feature of Queries.

For some reason I find this approach more confusing than writing my structure transformations separately but, every dog to his tree :slight_smile:

Didn’t like the response you got at php - fetching result from database in specific format cakephp5 - Stack Overflow?