Parse.com Eager加载一对多关系让父母与孩子一起

时间:2015-09-14 00:12:45

标签: javascript parse-platform eager-loading

我目前有急切加载的问题。有没有办法让父母带着孩子?

我有一个问题模型,"有很多"回答与之相关的模型。答案可能超过100,所以我在每个答案上做了一个问题的指针"一对多"关系而不是在问题本身上存储一个Answer指针数组。

如何通过每个问题的10个第一个答案获得我的所有问题?

// this is what Parse.com says, but i want the opposit
var query = new Parse.Query(Answer);
query.include("Question");

// this is what i would like but not possible 
// because the pointer is on the Answer 
// so can't include it in a Question query
var query = new Parse.Query(Question);
query.include("Answers");

这对我不起作用,因为我想用他们的答案问题而不是答案与他们的父母问题

我如何急切加载?

1 个答案:

答案 0 :(得分:0)

假设您已保存问题,由questionId代表并且保存的答案由answerId代表;这就是你创建关系的方式

// adding answers to a specific question
var Question = Parse.Object.extend('Question');
var Answer = Parse.Object.extend('Answer');
var aQuestion = new Question({id: questionId});

var answersRelation = aQuestion.relation("answers");
answersRelation.add(new Answer({id: answerId}));
aQuestion.save();

现在,您将获得指定问题的所有答案

// getting answers...
var Question = Parse.Object.extend('Question');
var aQuestion = new Question({id: questionId});

var answerRelation = aQuestion.relation("answers")
answerRelation.query().find().then(function(_answers){
    console.log("Answers for question " + aQuestion.get("name"), _answers);
}, function(_errors){
    console.log("Error:" + aQuestion.get("name"), _errors);
});

https://parse.com/docs/js/guide#objects-relational-data