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.

Sub collection access in MongoCollection vs. Collection

Hello,

I'm migrating to Phalcon 3 on PHP 7. I'm using the Incubator classes for the current mongodb driver (vs old mongo drive.)

With the old Collection class, I accessed sub collection as arrays:

SomeCollection: { "prop": { "subprop": 1, "other_prop": 2 } }

<?php
$c = SomeCollection::findFirst();
$val = $c->prop['subprop'];

With MongCollection it seems to give me a StdClass instead of an array. I get PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array when trying to access the subcollection as an array.

How do I change this behavior back? I literally have thousands of places I use this.

Thanks



3.2k
Accepted
answer

Found it!

Line 303 in https://github.com/phalcon/incubator/blob/master/Library/Phalcon/Mvc/MongoCollection.php

$cursor->setTypeMap(["root"=>get_called_class(),"document"=>"object"]);

I changed to:

$cursor->setTypeMap(["root"=>get_called_class(),"document"=>"array"]);

Solved my problem and returned behavior to behavior. Will check if it breaks anything else.

Learned a bit about Type Maps. Here is more info if anyone is interested: http://php.net/manual/en/mongodb.persistence.deserialization.php#mongodb.persistence.typemaps

Hope this helps someone.



29.8k

Hi,

you may submit a pull request on github in the 3.0.x branch.



723

Just migrated to Phalcon 3 & PHP 7 and ran into this exception. This fix worked for me as well.

Thank you.