2016-09-17 61 views
0

我正在使用Parse平臺作爲後端,並且我有職位媒體類。 每個(img,文件,....)在分析對象裏面媒體類,並且每一個都有指向Post類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

最好的方法將是有一個對媒體的郵政之間有很多關係,使每個包含多個媒體對象,然後你可以使用下面的代碼,以獲得與所有帖子其下的所有媒體..

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 
 
});

你可以閱讀更多關於解析關係在here

+0

謝謝冉,響應返回媒體feild像這樣的「媒體」:{「__type」:「關係」,「className」:「媒體」} 我怎麼能得到媒體內容? –

+0

在媒體文件中,您擁有媒體網址(以字符串形式)。用這個字符串創建NSURL,然後通過NSURLConnection或庫(例如AFNetwork,Almofire等)獲取數據。 –