Getting oddly-formatted results on retrieving records from database

I’m having difficulty in retrieving data from my database. I don’t think that I’m doing anything different in this part of the code than in other parts, but in this part it’s giving me results in an odd-looking format.

So, in the database I have a table called subsites, which has 3 columns: id, name, announcement_id. In the controller, I need to get a list of all the subsites which have a specific announcement_id (passed in). I do this as follows:

$subsitesTable = TableRegistry::get('Subsites');
$subsitesList = $subsitesTable->find('all')
			->where(['announcement_id' => $announcement_id])
			->execute();

I then use a for loop to loop over the subsites in subsitesList like this:

foreach($subsitesList as $subsite) {
  ... do things in here...
}

The problem is that when I try to do anything with ‘subsite’ in that loop, Cake complains that subsite is not an array.

I tried to figure out what the first subsite looks like by doing debug($subsite); in the for loop. This gives me the following:
[
‘Subsites__id’ => ‘1’,
(int) 0 => ‘1’,
‘Subsites__name’ => ‘Main’,
(int) 1 => ‘Main’,
‘Subsites__announcement_id’ => ‘3’,
(int) 4 => ‘3’
]

I’ve no idea what this format is, or why I’m getting this result back when the same code (or what looks like the same code) in other places returns an array as usual.

Can anyone point me in the right direction? Thanks!

http://book.cakephp.org/3.0/en/orm/database-basics.html

When using the query builder, no SQL will be sent to the database server until the execute() method is called, or the query is iterated. Iterating a query will first execute it and then start iterating over the result set

$subsitesTable = TableRegistry::get('Subsites');
$subsitesList = $subsitesTable->find('all')
			->where(['announcement_id' => $announcement_id]);
/*
If u need array conversion:
$subsitesList = $subsitesTable->find('all')
			->where(['announcement_id' => $announcement_id])
                        ->toArray();
*/
foreach($subsitesList as $subsite) {
  ... do things in here...
}
1 Like

Thank, Diego. That’s got it working now. I still haven’t quite got to grips with the new way of doing things in Cake 3.0!