Search code examples
iosswiftdatabaserealm

Realm query Object property field by its property


I'm developing an application for iOS using Swift and chose Realm as a database solution for it. I asked one question about Realm and now I have another.

Suppose we have a schema like this:

class Person: Object {
    dynamic var id: String = NSUUID().UUIDString
    dynamic var name: String?
    dynamic var cars: Car?

class Car: Object {
    dynamic var name: String?

I have one class (Person) that contains any number of objects of another class (Car). Car that are "linked" with the Person has some properties in context of that Person (and they can be different for same Car for different Persons or for two similar Cars for one Person). Using List<...>() we can not store such properties for each Item, am I right?

If we use Car only for one Person and only once we can create another class that includes only additional properties for Cars and links them with ID of Person plus ID of Car. But it does't work if we have two similar Cars with different additional properties.

So, how I see the solution. Have one table (class) stores ID of Person, ID of one Car and additional properties for this Car. For another Car for the same Person it has the same Person ID, Car ID (same or not) and another additional properties for this instance of a Car.

There is a problem (and a question that I mean). Having that structure I want to query all Cars from that table with their additional properties that have Person ID equals to some_id. How should I do this? Or maybe what another structure (maybe using List<...>) I should have to achieve such kind of behavior?


Solution

  • What is FastList exactly ?

    If you want Items to have a property of Lists collection.

    You have to redefine your Realm model. something like this.

    class Car:Object{
        dynamic var createDate: NSDate = NSDate()
    }
    class Person:Object{
        let cars = List<Car>()
    }
    

    and query by predicate like this

    let realm = Realm()
    var ownedCarsFilterByDate = realm.objects(Person).filter("ANY cars.createDate = '\(date)'")
    

    Edited to updated question

    Your solution is to create table class, which has 'Person' , 'Car' and 'Context Attribute'.

    Your model would be like this

    class PersonAndCarRelation:Object{
    
        dynamic var person: Person?
        dynamic var car: Car?
        dynamic var contextAttribute = ""
    
    }
    

    and you can query all cars associated with person

        let personID = "123456789"
        let personAndCarArray = realm.objects(PersonAndCarRelation).filter("person.id == \(personID)")
        for personAndCar in personAndCarArray{
            let personName = personAndCar.person.name
            let carName = personAndCar.car.name
            let context = personAndCar.contextAttribute
            println("I am \(personName). I have a \(carName) with \(context)")
        }