【问题标题】:Parse query- saving pfobject and children with one-to-many relationship解析查询 - 保存 pfobject 和具有一对多关系的子级
【发布时间】:2014-09-12 02:05:22
【问题描述】:

我有一个相当典型的评论发布应用程序,我正在尝试构建它以获取乐趣。我的问题是,当我将评论保存到现有帖子(一个帖子 - 多个 cmets 关系)时,评论已保存并了解其与帖子的关系,但帖子不知道该评论。

我想要什么:

Posts: post "Foo" | comments: "X", "Y" | other columns
Comments:
comment "X" | post "Foo" | ...
comment "Y" | post "Foo" | ...

现在: cmets看起来不错,但是帖子缺少一对多的关系

Posts: post "Foo" | <NOTHING> | other columns

我尝试了两种将 cmets 保存到帖子的不同方法:

1) 创建评论作为 Post 的子项,保存 Post。根据this link,这很好,并且确实保存了评论,即使我们对帖子对象执行了保存。但是帖子没有将评论视为孩子。

// Inside comment class
let pfComment = PFObject()
pfPost.addObject(pfComment, forKey: "comments") // Add the comment to the post

2) 对评论和帖子执行 saveAll,这给了我两个 cmets,因为帖子保存的一个被视为与另一个评论分开的新对象

// Same pfComment as above,
PFObject.saveAllInBackground([pfPost, pfComment], block: ...

什么给了?解析docs and questions 无用!

【问题讨论】:

    标签: ios parse-platform


    【解决方案1】:

    我认为当您启动和保存 PFObject 时,you need to be explicit about what kind of object you're dealing with。因此,对于您的评论对象,您可以说 pfComment = PFObject(className: "Comment")。现在,当您保存它时,Parse 会知道您要保存什么。

    我相信我通过为 cmets 创建一个带有数组的 Post 类来实现您的目标,如下所示:

    我还做了一个简单的注释类,它有一个消息字符串:

    从这里,我能够将代码放在一起,将 cmets 添加到帖子的数组中。

        var post = PFObject(className:"Post")
        var comment = PFObject(className:"PostComment")
        comment["message"] = "New Message"
    
        var query = PFQuery(className:"Post")
        query.getObjectInBackgroundWithId("fu8gCbYVeI") {
            (result: PFObject!, error: NSError!) -> Void in
            if error == nil {
                post = result
            } else { }
        }
    
        post.addObject(comment, forKey: "comments")
    
        PFObject.saveAll([comment, post])
    

    这应该将 cmets 作为指向实际评论对象的指针保存到帖子中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-29
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多