Android Parse多对多数组查询:如何匹配多个Author对象?
当然可以!Parse完全支持这种“在数组列中匹配多个对象”的查询需求,核心是用whereContainedIn()方法来实现,我分两种常见场景给你具体说明:
场景1:你已经拥有一组目标Author对象
如果你的业务逻辑中已经拿到了要匹配的多个Author ParseObject(比如从前端传入、或者其他查询结果),直接把这个对象列表传给whereContainedIn即可:
// 假设你已经获取到了需要匹配的Author对象列表 List<ParseObject> targetAuthors = ...; // 构建Book查询 ParseQuery<ParseObject> bookQuery = ParseQuery.getQuery("Book"); // 关键:指定"authors"数组列包含列表中的任意一个Author对象 bookQuery.whereContainedIn("authors", targetAuthors); // 关联加载完整的Author数据(如果需要返回Author的详细信息) bookQuery.include("authors"); // 执行异步查询 bookQuery.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> bookList, ParseException e) { if (e == null) { // 查询成功,处理返回的书籍列表 for (ParseObject book : bookList) { // 示例:获取关联的Author对象列表 List<ParseObject> authors = book.getList("authors"); } } else { // 处理查询错误 e.printStackTrace(); } } });
场景2:需要先查询符合条件的Author,再关联查Book
如果你的目标Author需要先通过另一组条件查询得到(比如查找所有某类别的作者),可以先执行Author的查询,拿到结果后再发起Book的查询:
// 第一步:先查询符合条件的Author ParseQuery<ParseObject> authorQuery = ParseQuery.getQuery("Author"); // 配置Author的查询约束,比如查找国籍为"US"的作者 authorQuery.whereEqualTo("nationality", "US"); authorQuery.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> matchedAuthors, ParseException e) { if (e == null && !matchedAuthors.isEmpty()) { // 第二步:用查询到的Author列表查询对应的Book ParseQuery<ParseObject> bookQuery = ParseQuery.getQuery("Book"); bookQuery.whereContainedIn("authors", matchedAuthors); bookQuery.include("authors"); bookQuery.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> bookList, ParseException e) { if (e == null) { // 处理最终的书籍列表 } else { // 处理Book查询错误 e.printStackTrace(); } } }); } else { // 处理Author查询无结果或错误的情况 if (e != null) e.printStackTrace(); } } });
额外说明
如果你的需求是数组列必须包含所有目标对象(而不是任意一个),那可以把whereContainedIn换成whereContainsAll()方法,这个方法会严格匹配数组列包含列表中所有对象的记录。
内容的提问来源于stack exchange,提问作者AndreiBogdan
相关产品推荐
相关产品推荐

