简体   繁体   中英

Firestore Query with search in document and sub-collection

I have an employee document (name, designation, ...) and a sub-collection containing all the shifts (documents of the sub-collection) assigned to this employee.

When assigning a new shift, I want to retrieve only the employees that have a particular designation, meaning they are skilled to perform this shift.

Furthermore, I should search within the sub-collection and fetch only the employees that do not have a document for the same date of the shift to assign.

At the moment I only know how to retrieve the employees that have a particular designation.

What I am not able to implement is the part where I only get the skilled employees that are free on the day of the shift to assign.

 @override
  Stream<List<Employee>> availableEmployeesForGivenDesignation(String designation, DateTime statusDate) {
    return _employeeCollection
        .where('designation', isEqualTo: designation)
        .snapshots()
        .map((snapshot) {
         //todo search in the sub-collection
          ...
        });
  }

Firestore queries only work across a single type of collection. There is no way to search both employees and their shifts in a single query, you will need at least two queries for that.

To allow your use-case with a single query, you'll have to duplicate data. You had two options there:

  1. Duplicate the necessary shift data into the employee document, and then query only the employee collection.
  2. Duplicate the necessary employee data into their shift documents, and then perform a collection group query across all shifts collections.

Given what you described the second option sounds most promising. It'd look something like this:

db.collectionGroup("shifts")
  .where('designation', isEqualTo: designation)
  .where(...your other condition...)
  .snapshots()
  .map((snapshot) {
    print(snapshot.reference.parent().parent().documentID);
  })

You'd then use that document ID to look up the employee document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM