3

I have this Backendless tables: Posts and Comments

Posts has a column comments which is has a one-to-many relationship to Comments table.

I'm try to get the comments in a latestOrder first behavior.

Currently, I have this query:

  let query = BackendlessDataQuery()
  let queryOptions = QueryOptions()
  queryOptions.pageSize = size
  queryOptions.related = ["comments", "comments.user", "user", "media"]
  query.queryOptions = queryOptions
  // Used PostObject since it is already mapped using `mapTableToClass`
  backendlessInstance.persistenceService.of(PostObject.ofClass()).find(
    query,
    response: { backendlessPostsList in
      let backendlessPostsListOfOffset = backendlessPostsList.getPage(offset)
      guard let postObjects = backendlessPostsListOfOffset.getCurrentPage() as? [PostObject] else {
        reject(BackendlessError.InvalidTypeForObject(name: "Post"))
        return
      }
      return postObjects
    },
    error: { fault in
      // TODO Find a way to convert a Fault to ErrorType
      print("Server reported an error (1): \(fault)")
    }
  )

What I'm doing currently to sort Post.comments in the view model is reversing it. Post.comments.reverse().

Is there a way to explicitly sort the comments in Backendless level?

jhnferraris
  • 1,291
  • 1
  • 10
  • 32
  • You can set a sort attribute on the query options, I'm not exactly sure what you're asking... – Wain Jun 08 '16 at 06:59
  • @Wain I just want to sort comments in latestFirst order without compromising the order of PostObjects. – jhnferraris Jun 08 '16 at 07:20

2 Answers2

3

You don't have options when using related, and you should really just use it for to-one relationships, not to-many because of this. It would work ok if you have a one-to-few relationship.

So, you should make a separate request for the comments so you can specify a specific page size and sort order. Note that when you specify the variable to sort by (created) you can also add asc or desc to specify the direction of the sort (so created desc).

Wain
  • 117,132
  • 14
  • 131
  • 151
0

You could use the sort function.

let sortedComments = Post.comments.sort { $0.date > $1.date }

Of corse your comments will need a published date field for this to work.

Ashmore11
  • 176
  • 1
  • 11