如何更改数据模型?

时间:2016-10-12 14:42:34

标签: swift parse-platform parse-server

我正在制作社交媒体应用。

用户 - 显示名称 - 用户名 - profileImg - 密码 - 电子邮件

评论 - 用户名 - 评论 - 到

朋友 - 追随者 - 关注

主题标签 - 井号 - 至 - 通过 - 评论

喜欢 - 至 - 通过

帖子 - postImg - 用户名 - 标题 - uuid

我的问题是当用户发布带有标题文字的图像时 我想要检索用户名,profileImg,标题,评论,评论,postImg,喜欢计数

我的方法是重新设计帖子db

帖子 - postImg - 用户名 - 标题 - uuid - 评论 - 评论 - profileImg - 喜欢的次数

但我认为这是糟糕的db设计。

    func loadPosts() {

        //STEP 1. Find posts related to people who we are following

        let followQuery = PFQuery(className: “friends")

        followQuery.whereKey(“following", equalTo: PFUser.current()!.username!)
        followQuery.findObjectsInBackground (block: { (objects:[PFObject]?, error:Error?) -> Void in

            if error == nil {
                //clean up
                self.followArray.removeAll(keepingCapacity: false)

                //Appending where people following..
                //find related objects
                for object in objects! {
                    self.followArray.append(object.object(forKey: “following") as! String)
                }
                //append current user to see own posts in feed
                self.followArray.append(PFUser.current()!.username!)


                //STEP 2. Find posts made by people appended to followArray
                let query = PFQuery(className: "posts")
                query.whereKey("username", containedIn: self.followArray)
                query.limit = self.page
                query.addDescendingOrder("createdAt")


                query.findObjectsInBackground(block: { (objects:[PFObject]?, error:Error?) -> Void in

                    if error == nil {

                        //clean up
                        self.usernameArray.removeAll(keepingCapacity: false)
//                        self.profileArray.removeAll(keepCapacity: false)
                        self.dateArray.removeAll(keepingCapacity: false)
                        self.postArray.removeAll(keepingCapacity: false)
                        self.descriptionArray.removeAll(keepingCapacity: false)

                        self.uuidArray.removeAll(keepingCapacity: false)
                        self.commentsArray.removeAll(keepingCapacity: false)
                        self.commentsByArray.removeAll(keepingCapacity: false)

                        //find related objects
                        for object in objects! {
                            self.usernameArray.append(object.object(forKey: "username") as! String)
//                            self.profileArray.append(object.objectForKey("profileImg") as! PFFile)
                            self.dateArray.append(object.createdAt)
                            self.postArray.append(object.object(forKey: "postImg") as! PFFile)
                            self.descriptionArray.append(object.object(forKey: "title") as! String)
                            self.uuidArray.append(object.object(forKey: "uuid") as! String)

                            //set Comments
                            let comment = object.object(forKey: "comment") as! String
                            let by = object.object(forKey: "commentby") as! String
                            let commentString = " " + comment

                            self.commentsByArray.append(by)
                            self.commentsArray.append(commentString)


                        }
                        //reload tableView & end spinning of refresher
                        self.tableView.reloadData()
                        self.refresher.endRefreshing()

                    } else {
                        print(error!.localizedDescription)
                    }
                })


            } else {
                print(error!.localizedDescription)
            }

        })

    }

定义的单元格

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


//define cell
let cell = tableView.dequeueReusableCell(withIdentifier: "ShopDetailCell", for: indexPath) as! ShopDetailCell



cell.userNameLabel.text = usernameArray[(indexPath as NSIndexPath).row - 1]
cell.userNameLabel.sizeToFit()

cell.uuidLabel.text = uuidArray[(indexPath as NSIndexPath).row - 1]

cell.descriptionLabel.text = descriptionArray[indexPath.row - 1]
cell.descriptionLabel.sizeToFit()



cell.commentLabel.sizeToFit()


//Load ProfileImage
let profileImgQuery = PFQuery(className: "_User")
profileImgQuery.whereKey("username", equalTo: usernameArray[(indexPath as NSIndexPath).row - 1])
profileImgQuery.findObjectsInBackground(block: {(objects:[PFObject]?, error:Error?) -> Void in

    if error == nil {

        //shown wrong user
        if objects!.isEmpty {
            print("Wrong User")
        }

        //find related to user information
        for object in objects! {

            //Set Image
            let profilePictureObject = object.object(forKey: "profileImg") as? PFFile
            profilePictureObject?.getDataInBackground { (imageData:Data?, error:Error?) -> Void in

                if(imageData != nil)
                {
                    let profileURL : URL = URL(string: profilePictureObject!.url!)!

                    cell.userImg.sd_setImage(with: profileURL, placeholderImage: UIImage(named: "holderImg"))
                }

            }

        }
    } else {
        print(error?.localizedDescription)
    }

})

//Clip to circle
cell.userImg.layoutIfNeeded()
cell.userImg.layer.cornerRadius = cell.userImg.frame.size.width/2
cell.userImg.clipsToBounds = true



// place post picture using the sdwebimage
let postURL : URL = URL(string: postArray[(indexPath as NSIndexPath).row - 1].url!)!
cell.postImg.sd_setImage(with: postURL, placeholderImage: UIImage(named: "holderImg"))


//Calculate post date
let from = dateArray[(indexPath as NSIndexPath).row - 1]
let now = Date()

let components : NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth]

let difference = (Calendar.current as NSCalendar).components(components, from: from!, to: now, options: [])



// logic what to show : Seconds, minutes, hours, days, or weeks
if difference.second! <= 0 {
    cell.dateLabel.text = "NOW"
}

if difference.second! > 0 && difference.minute! == 0 {

    cell.dateLabel.text = "\(difference.second!) SEC AGO"
}

if difference.minute! > 0 && difference.hour! == 0 {

    cell.dateLabel.text = "\(difference.minute!) MIN AGO"
}

if difference.hour! > 0 && difference.day! == 0 {
    cell.dateLabel.text = "\(difference.hour!) HR AGO"

}

if difference.day! > 0 && difference.weekOfMonth! == 0 {

    cell.dateLabel.text = "\(difference.day!) DAY AGO"
}

if difference.weekOfMonth! > 0 {
    cell.dateLabel.text = "\(difference.weekOfMonth!) WEEK AGO"
}
cell.dateLabel.sizeToFit()


//Set Text Label
if cell.descriptionLabel.text!.isEmpty == true || cell.descriptionLabel.text == " "{
    if cell.commentLabel.text!.isEmpty == true || cell.commentLabel.text == " "{
        cell.dateTop.constant = 7
    }else {
        cell.dateTop.constant = cell.commentTop.constant + cell.commentLabel.frame.height + 8
    }
}else {
    if cell.commentLabel.text!.isEmpty == true || cell.commentLabel.text == " "{
        cell.dateTop.constant = cell.descriptionTop.constant + cell.descriptionLabel.frame.height + 8
    }else {
        cell.commentTop.constant = cell.descriptionTop.constant + cell.descriptionLabel.frame.height + 8
        cell.dateTop.constant = cell.commentTop.constant + cell.commentLabel.frame.height + 8
    }
}

// manipulate like button depending on did user like it or not
let didLike = PFQuery(className: "likes")
didLike.whereKey("by", equalTo: PFUser.current()!.username!)
didLike.whereKey("to", equalTo: cell.uuidLabel.text!)
didLike.countObjectsInBackground(block: {(count:Int32, error:Error?) -> Void in

    //if no any likes are found, else found likes
    if count==0 {

        cell.likeBtn.setTitle("unlike", for: UIControlState())
        cell.likeBtn.setImage(UIImage(named:"heartBtn"), for: UIControlState())
    }else{

        cell.likeBtn.setTitle("like", for: UIControlState())
        cell.likeBtn.setImage(UIImage(named: "heartTapBtn"), for: UIControlState())

    }

})

//count total likes of shown post
let countLikes = PFQuery(className: "likes")
countLikes.whereKey("to", equalTo: cell.uuidLabel.text!)
countLikes.countObjectsInBackground(block: {(count:Int32, error:Error?) -> Void in

    cell.likesLabel.text="\(count) likes"
})



cell.userNameLabel.layer.setValue(indexPath, forKey: "index")
cell.commentBtn.layer.setValue(indexPath, forKey: "index")
cell.moreBtn.layer.setValue(indexPath, forKey: "index")




return cell

}

你们有人可以建议我吗?

我已阅读本教程“https://parse.com/tutorials/anypic”,但我无法确定哪种数据模型对我更好

我希望使用连接或指针方法。

1 个答案:

答案 0 :(得分:1)

只要用户发帖,您就可以将currentUser保存为Posts类中的指针。

  

注意:我将在Objective-C中进行演示,但您很容易将其转换为Swift。但是如果您在阅读objc代码时遇到问题,我将编辑我对Swift版本的回答。

func post { //make a post
    var post = PFObject(className:"Posts")
    post["user"] = PFUser.current()//save the current user as a pointer pointing to the User class. You can add a column of type pointer in your parse dashboard inside your Posts class.
    //set up other attributes here...
    post.saveInBackground()
}

然后,当我们进行查询时,我们可以使用includeKey来包含用户指针。

let query = PFQuery(className: "posts")
query.whereKey("username", containedIn: self.followArray)
query.includeKey("user")// THIS IS IMPORTANT
query.limit = self.page
query.addDescendingOrder("createdAt")
query.findObjectsInBackground(block: { (objects:[PFObject]?, error:Error?) -> Void in
    if !error {
        //we can access the user pointer by doing:
        for object in objects {
            var user = object["user"]
            var username = user.username
            var profileImage = user["profileImg"] //a PFFile
            //...
        }
    }

此外,您始终可以使用PFQueryTableViewController为您加载对象,因此您无需手动存储查询结果。