A.s.ALI
A.s.ALI

Reputation: 2082

Realm Relation how to implement

I am working on iOS and that is saving product. and this product has some more things inside its model

let suppose the following model

@objcMembers public class ProductModel : Object, Codable {

  dynamic var Id : Int = 0
  dynamic var Name : String = 0
  dynamic var Price : Double = 0.0

}

and the other model (CustomerModel) that contains the ProductModel is as follow

 @objcMembers public class CustomerModel : Object, Codable {

  dynamic var Id : Int = 0
  dynamic var Name : String = 0
  var Product : ProductModel? = nil 

}

Now when I save customer with the product inside it, I can see that in Realm it gets saved successfully. But if and only if that object is not in Realm already,

Let suppose this

let customer1 = CustomerModel()
customer1.Id = ...
customer1.Name =  .....
customer1.Product = product1 

Now this customer data is saved. But I am getting exception if I try to save following data

let customer2 = CustomerModel()
    customer2.Id = ...
    customer2.Name =  .....
    customer2.Product = product1

Just notice that customer2 also want to save product info that is already saved in Realm namely "product1".

So how to handle this sitution.

I am trying to save the data with the following generic function for realm objects

func save <T: Object> (_ obj : T){
do {
    try realmObj.write{
        realm.add(obj)
    }
  }catch{}

}

Question 2:

Also I want to get All Customer, I know how to do it, but problem is It never retrieves the Product inside the Customer. I can see in Realm DB Browser that the customer that get saved with the product, that customer table contains the reference of Product also. But when I try to get all customer then that customer have only customer details not Product detail. Whereas that must be there.

Upvotes: 3

Views: 111

Answers (1)

Robert Dresler
Robert Dresler

Reputation: 11150

Just put dynamic keyword before your property

dynamic var Product : ProductModel? = nil 

Upvotes: 4

Related Questions