0

在 Parse 的文档中,我们看到了如何逆向多对多关系,但只需要查找一个对象。从他们的书籍和作者示例中工作,他们知道作者并且他们想找到这些书籍。我想要的是找到两个或更多作者贡献的书籍。

https://www.parse.com/docs/relations_guide#manytomany-relations

我尝试过的代码如下:

// suppose we have a author object, for which we want to get all books
PFObject *authorA = ...
PFObject *authorB = ...

// first we will create a query on the Book object
PFQuery *query = [PFQuery queryWithClassName:@"Book"];

// now we will query the authors relation to see if the author object
// we have is contained therein
[query whereKey:@"authors" equalTo:authorA];
[query whereKey:@"authors" equalTo:authorB];

代码有点工作。

但是,似乎正在发生的事情是,如果 authorA 有很多书,而 authorB 有一本,则在查询中找到一本书。如果 authorA 有一本书,而 authorB 有很多,则在查询中找到很多书。

我想要的是一种方法来查找在其作者关系中同时具有 authorA 和 authorB 的书籍。

4

2 回答 2

0

您可以使用以下代码:-

PFQuery *authorA_Query = [PFQuery queryWithClassName:@"Book"];
[query whereKey:@"authors" equalTo:authorA];

// PFQuery *authorB_Query = [PFQuery queryWithClassName:@"Book"];
[query whereKey:@"authors" equalTo:authorB];

// PFQuery *query = [PFQuery orQueryWithSubqueries:@[authorA_Query,authorB_Query]];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
   // results contains book with both author A and B.
   // and this is called compound querying.
   // this way you could pass many queries to filter out your result.
 }];
于 2014-09-29T07:17:40.563 回答
0

看起来确实没有使用 PFRelation 的解决方案(希望有人证明我错了)。

我所做的是退回到数组。

https://www.parse.com/docs/relations_guide#onetomany-arrays

所以像这样的工作

Author *authorA = ...
Author *authorB = ...
Book* book = ...

// stick the objects in an array
NSArray *authors = @[authorA, authorB];

// store the authors for the book
[book setObject:weapons forKey:@"authors"];

// then you can query as usual
PFQuery *bookQuery = [Book query];
[bookQuery whereKey:@"authors" equalTo:authorA];

// or query using an array of Author objects...
[bookQuery whereKey:@"authors" containedIn:@[authorA, authorB]];
[bookQuery whereKey:@"authors" containsAllObjectsInArray:@[authorA, authorB]];

但是,这不是我想要的解决方案。我一直在寻找能够为给定的“书”拥有大量“作者”的能力。但就目前而言,这将起作用......

于 2014-09-29T20:18:14.927 回答