lincolnberryiii
lincolnberryiii

Reputation: 670

Unable to Get Documents from a Nested Collection with Cloud Firestore using PHP

Following Google's official documentation at https://github.com/GoogleCloudPlatform/php-docs-samples/blob/master/firestore/src/get_all_docs.php, I am unable to retrieve documents that are part of a nested collection, i.e.:

$db = new FirestoreClient([
    'projectId' => $projectId,
]);
//$citiesRef = $db->collection('cities'); //working original example
$citiesRef = $db->collection('countries')->document('USA')->collection('cities'); //this throws an HTTP Error 500 
$documents = $citiesRef->documents();
foreach ($documents as $document) {
    if ($document->exists()) {
        printf('Document data for document %s:' . PHP_EOL, $document->id());
        print_r($document->fields());
        printf(PHP_EOL);
    } else {
        printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
    }
}

The above code throws an HTTP Error 500. Here is my example database:

Cloud Firestore Database Used in Example

The error log (CentOS 6) shows:

[06-May-2018 22:24:26 UTC] PHP Warning:  Module 'protobuf' already loaded in Unknown on line 0
[06-May-2018 22:24:26 UTC] PHP Warning:  Module 'protobuf' already loaded in Unknown on line 0
[06-May-2018 22:24:27 UTC] PHP Fatal error:  Call to undefined method Google\Protobuf\Timestamp::getFields() in /home/user/public_html/my/vendor/google/gax/src/ApiCore/Serializer.php on line 222
[06-May-2018 22:25:02 UTC] PHP Warning:  Module 'protobuf' already loaded in Unknown on line 0
[06-May-2018 22:25:02 UTC] PHP Warning:  Module 'protobuf' already loaded in Unknown on line 0

I'm aware that Firestore is still in beta. Is this one of the known issues/limitations?

Upvotes: 0

Views: 2352

Answers (1)

lincolnberryiii
lincolnberryiii

Reputation: 670

As a workaround, I am able to get the data from the nested document like so:

$db = new FirestoreClient([
    'projectId' => $projectId,
]);
//$citiesRef = $db->collection('cities'); //working original example
$citiesRef = $db->collection('countries')->document('USA')->collection('cities');
$documents = $citiesRef->select(['capital','country','name','population','state'])->documents();
foreach ($documents as $document) {
    if ($document->exists()) {
        printf('Document data for document %s:' . PHP_EOL, $document->id());
        //print_r($document->fields()); //this no longer works
        print_r($document->data());
        printf(PHP_EOL);
    } else {
        printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
    }
}

Upvotes: 1

Related Questions