我使用Parse平台作为后端,我有帖子和媒体类。 每个(img,file,....)在 Media 类中的Parse对象中,每个都有一个列,指向Posts类中的Post对象。
我正在尝试使用每个帖子的媒体获取所有帖子,我如何通过一个查询来完成?
var Posts = Parse.Object.extend("posts");
var query = new Parse.Query(Posts);
var newObject = [];
query.find().then(function(data){
for (var i = 0; i < data.length; i++) {
var item = data[i].toJSON();
var newData = {};
newData.objectId = item.objectId;
newData.user = {
userId: item.user.objectId,
fullName: item.user.fullName,
picture: item.user.imageUrl,
userName: item.user.userName,
};
newData.date = item.createdAt;
newData.hasImages = item.hasImages;
newData.postBody = item.postBody;
if(item.hasImages){
var Media = Parse.Object.extend("media");
var mediaQuery = new Parse.Query(Media);
mediaQuery.limit(10);
mediaQuery.descending("createdAt");
mediaQuery.matches("post", item.objectId);
mediaQuery.find().then(function(data){
newData.images = data;
});
}
newObject.push(newData);
}
console.log(newObject);
});
答案 0 :(得分:0)
最佳方法是在媒体发布之间建立一对多关系,以便每个发布包含多个媒体对象,然后您可以使用以下代码:为了获得包含所有媒体的所有帖子..
var Posts = Parse.Object.extend("posts");
var query = new Parse.Query(Posts);
// add some coditions to the Posts query here if needed
query.include("media"); // include the media relation (0..n)
// if you want to fetch only posts that have media under it you can use the following line of code
query.exists("media"); // make sure that only posts with media will be populated
query.find().then(function(posts){
// here you have the list of posts
// in order to access property of a post you can use the following code:
for (var i=0;i < posts.length;i++){
var post = posts[i];
var postMedia = post.get("media"); // get all media objects in a specific post
//..
}
},function(error){
// error
});
&#13;
您可以在here
中阅读有关Parse关系的更多信息