We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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



8.7k
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: https://php.net/manual/en/mongodb.persistence.deserialization.php#mongodb.persistence.typemaps

Hope this helps someone.



43.9k

Hi,

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



1.2k

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

Thank you.