Relations

  • Object property type to indicate a to-one relation to another object.

    Initialize with nil in your type declarations.

    • You can set the value to nil to remove the relation. You can also set target or targetId to nil.
    • You can set target to an object to set the relation. Call Box.put(_:) to persist the changes.
    • You can set targetId to an object’s ID to set the relation. Call Box.put(_:) to persist the changes.

    Example

    class Person: Entity {
        var spouse: ToOne<Person> = nil
    }
    
    let personBox: Box<Person> = store.box(for: Person.self)
    let amanda: Person = ...
    let bob: Person = ...
    
    amanda.spouse.target = bob
    personBox.put(amanda)
    

    Remove a relation

    amanda.spouse.target = nil
    // ... or ...
    amanda.spouse.targetId = nil
    // ... are equivalent to:
    amanda.spouse = nil
    // ... whis is a short version of:
    amanda.spouse = ToOne<Person>(target: nil)
    
    See more

    Declaration

    Swift

    public final class ToOne<T>: ExpressibleByNilLiteral
    where T: Store.InspectableEntity
  • Declaration of a to-many relationship to objects of a certain type.

    Initialize with nil in your type declarations. The code generator will set different values.

    Example:

    class Customer: Entity { var id: Id = 0

       /// Annotation with Source's property name is required; Order is "Source", Customer is "Target"
       // sourcery: backlink = "customer"
       var orders: ToMany<Order, Customer> = nil
       // ...
    

    }

    class Order: Entity { var id: Id = 0 var customer: ToOne = nil // … }

    Removing relations

    Since this type only supports backlinks at the moment, you cannot modify relations from this end. You have to set the relation from Source to Target to nil instead:

    // You cannot set `aCustomer.orders = nil`, so:
    let order = Array(aCustomer.orders)
    orders.forEach { order in
        order.customer = nil
    }
    store.box(for: Order.self).put(orders)
    

    Note

    Not ready for storing to-many relations. Used only to get access to backlinks from ToOne relations. Use the // sourcery:backlink="propertyName" annotation to tell the code generator which property of ToMany.Source should be used to determine the backlinks.
    See more

    Declaration

    Swift

    public final class ToMany<S, T>: ExpressibleByNilLiteral
    where S: Store.InspectableEntity, T: Store.InspectableEntity