0

The $ref->where('reference_field', '=', 'Path/To/Referenced/Document'); does not work.

<?php

namespace Google\Cloud\Samples\Firestore;

use Google\Cloud\Firestore\FirestoreClient;

function query_by_reference_field($projectId)
{
    // Create the Cloud Firestore client
    $db = new FirestoreClient([
        'projectId' => $projectId,
    ]);

    $ref = $db->collection('CollectionName');
    $query = $ref->where('reference_field', '=', 'Path/To/Referenced/Document');
    $snapshot = $query->documents();
    foreach ($snapshot as $document) {
        printf('Document %s returned.' . PHP_EOL, $document->id());
    }
}

So, how do I get results where a reference field contains a given document path / document id?

Francisco Luz
  • 2,775
  • 2
  • 25
  • 35

1 Answers1

0

I have just figured it out by looking at this javascript question here.

The answer is: You have to pass a document reference object instead of a path string.

<?php

namespace Google\Cloud\Samples\Firestore;

use Google\Cloud\Firestore\FirestoreClient;

function query_by_reference_field($projectId)
{
    // Create the Cloud Firestore client
    $db = new FirestoreClient([
        'projectId' => $projectId,
    ]);
    
    $referenced_document = $db->document('Path/To/Referenced/Document');

    $ref = $db->collection('CollectionName');
    $query = $ref->where('reference_field', '=', $referenced_document);
    $snapshot = $query->documents();
    foreach ($snapshot as $document) {
        printf('Document %s returned.' . PHP_EOL, $document->id());
    }
}
Francisco Luz
  • 2,775
  • 2
  • 25
  • 35