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 neil: Person = ...
    
    amanda.spouse.target = neil
    try 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: EntityInspectable & __EntityRelatable>: ExpressibleByNilLiteral
    where T == T.EntityBindingType.EntityType
    extension ToOne: CustomStringConvertible
    extension ToOne: CustomDebugStringConvertible
  • 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: EntityId<Customer> = 0
    
        /// Annotation with ReferencedType's property name is required; Order is "ReferencedType",
        /// Customer is "OwningType"
        // objectbox: backlink = "customer"
        var orders: ToMany<Order> = nil
        // ...
    }
    
    class Order: Entity {
        var id: EntityId<Order> = 0
        var customer: ToOne<Customer> = nil
        // ...
    }
    

    Removing relations

    A ToMany can be modified just like any other RangeReplaceableCollection. Once you have changed your relation as needed, call applyToDb() on it to actually write the changes to disk.

    Note

    You can also use a ToMany to create backlinks from ToOne relations. Use the // objectbox: backlink = "propertyName" annotation to tell the code generator which property of ToMany.ReferencedType should be used to determine the backlinks.
    See more

    Declaration

    Swift

    public final class ToMany<S: EntityInspectable & __EntityRelatable>: ExpressibleByNilLiteral
    where S == S.EntityBindingType.EntityType
    extension ToMany: RandomAccessCollection
    extension ToMany: RangeReplaceableCollection
    extension ToMany: CustomStringConvertible
    extension ToMany: CustomDebugStringConvertible