Search code examples
androidparse-platform

Android. Parse. Many-to-many using an array


The example from the official documentation shows how to find a ParseObject inside an Array type column

// set up our query for the Book object
ParseQuery bookQuery = ParseQuery.getQuery("Book");

// configure any constraints on your query...
booKQuery.whereEqualTo("authors", author);

// tell the query to fetch all of the Author objects along with the Book
bookQuery.include("authors");

// execute the query
bookQuery.findInBackground(newFindCallback<ParseObject>() {
    public void done(List<ParseObject> bookList, ParseException e) {

    }
});

My question is: is there a way to have instead of one "author" ParseObject, multiple ones? I'm trying to search the objects in the Array which are contained inside the results of another query.

More precisely: I'd like to obtain all the books that are written by all the authors who's names start with "xxxx". And do this in a single query.

Can it even be done in a single query?! If I do booKQuery.whereMatchesQuery("authors", innerQuery); where innerQuery queries the Authors to search for all author names which start with a certain string value, it won't work.

Any ideas ?!


Solution

  • I don't think it can be done in one query with a many-to-many relation implemented as array because the include in this case returns all the Authors whose ids are in the array and it doesn't seem possible to place conditions on the objects represented by the ids.

    The Join table implementation seems better suited to this use case: Create another table (BookAuthors) with two columns: book (of type Pointer -> Book) and author (of type Pointer -> Author). Each book with more than one author will be represented by several rows (one per author) but you will be able to specify any condition for any field in either Book or Author

    ParseQuery.getQuery("BookAuthor")
        .include("book")
        .include("author")
        .whereStartsWith("author.name", "xxxx")
        .findInBackground(...)
    

    In the end you'll only need to filter the results to have only the distinct books.