skip to Main Content

I want to combine two firestore queries from the same collection. I want the result combination to be a Query.

var a = lessons
    .withConverter<Lesson>(
      fromFirestore: (snapshot, _) => Lesson.fromFirestore(snapshot),
      toFirestore: (Lesson lesson, options) => lesson.toFirestore(),
    )
    .where('private', isEqualTo: false);

var b = lessons
    .withConverter<Lesson>(
      fromFirestore: (snapshot, _) => Lesson.fromFirestore(snapshot),
      toFirestore: (Lesson lesson, options) => lesson.toFirestore(),
    )
    .where('private', isEqualTo: true)
    .where('author', isEqualTo: uid);

The first query gets all public lessons regardless of the author, the second query only gets the private lessons that the user created. I would then like to combine those results or create a union of the results.

I’m relatively new to flutter firestore, I’ve looked for some solutions online but I couldn’t find one that fits my specific scenario.

2

Answers


  1. var uid = 'your_user_id';
    
    var query = lessons
      .withConverter<Lesson>(
        fromFirestore: (snapshot, _) => Lesson.fromFirestore(snapshot),
        toFirestore: (Lesson lesson, options) => lesson.toFirestore(),
      )
      .where('private', whereIn: [false, true])
      .where('author', isEqualTo: uid);
    
    Login or Signup to reply.
  2. You can use the new OR capabilities of Firestore to put this in a single query. The most literal translation would look like this:

    lessons.where(
      Filter.or(
        Filter("public", isEqualTo: true),
        Filter.and(
          Filter("author", isEqualTo: user.uid),
          Filter("public", isEqualTo: false)
        )
      )
    )
    

    Since your public is a boolean, it can only be true or false, you can rewrite the above to this shorter form:

    lessons.where(
      Filter.or(
        Filter("author", isEqualTo: user.uid),
        Filter("public", isEqualTo: true)
      )
    )
    

    The results for both are guaranteed to be the same, so I’d go for the latter, shorter query.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search