strongloop-community / loopback-sdk-ios

iOS Client SDK for the LoopBack framework.
Other
75 stars 38 forks source link

Examples showing how to query for object relations from loopback SDK #31

Open osunacons opened 9 years ago

osunacons commented 9 years ago

Hi,

I am trying to query a loopback server for relations between models, I have a "Users" Model and an "Cars" model, and a has me nay relation between them, so I can query for all items in a section with /users/:id/cars from a rest client.

any documentation or code examples?

vikmeup commented 8 years ago

any status on this?

I would like to see examples as well

hideya commented 8 years ago

Although iOS SDK doesn't directly support relations yet, I hope the following post may help: Issue https://github.com/strongloop/loopback-sdk-ios/issues/2 -- Examples showing how to query for object relations from loopback SDK (NOTE: now you need to subclass LBPersistedModel instead of LBModel if you are using the code from the master).

I'd like to have SDK to support relations directly and would like to work on it as a part of iOS SDK work.

jubbens commented 8 years ago

@carliwis @hideya As noted in the referenced issue, the workaround does not work. This is because you need to create a new item for your relation to the repository contract. This Swift example allows you to reference /users/:id/cars as you expect:

In class userRepository:LBPersistedModelRepository:

override func contract() -> SLRESTContract! {
  let contract = super.contract()
  contract.addItem(SLRESTContractItem.init(pattern: "/\(self.className)/:id/cars", verb: "GET"), forMethod: "\(self.className).prototype.cars")

  return contract
}

And to retrieve related Car:LBPersistedModels from a User:LBPersistedModel:

self.invokeMethod("cars", parameters: ["id": self._id], success: { models in
  var cars:[Car] = []

  models.enumerateObjectsUsingBlock({ object, idx, stop in
    cars.append(carsRepository.modelWithDictionary(object as! [NSObject : AnyObject]) as! Car)
  })

  // Do something with cars
}, failure: { (error: NSError!) -> Void in
  // Handle the error
})