使用RealmSwift保存一对多关系对象

时间:2019-02-16 17:19:17

标签: swift realm swift4 swift4.2

就关系而言,我来自类似Ruby on Rails的数据结构。

所以在Rails中:Foo有很多Bar,而Bar有一个Foo。

通过RealmSwift文档,我想出了这一点:

JSON.stringify({here your json})

如果上面的内容正确无误,那么我很难知道如何创建此关系对象。

class Foo: Object {
  // other props
  var bars = List<Bar>() // I hope this is correct
}

class Bar: Object {
  // other props
  @objc dynamic var foo: Foo?
}

这是我止步不前的地方

// I need to create Foo before any Bar/s
var foo = Foo()
foo.someProp = "Mike"

var bars = [Bar]()
var bar = Bar()
bar.someProp1 = "some value 1"
bars.insert(bar, at: <a-dynamic-int>)

最后,我应该能够// Create Foo try! realm.write { realm.add(foo) // But.... I need to append bars, how? } try! realm.write { for bar in bars { // realm.add(bar) // I need to: foo.append(bar) but how and where? } } 看到foo.barsbars的数组才能得到bar.foo

foofoo尚未创建,因此不知道如何将批次链接以立即保存。可能?怎么样?如果您提供答案,可以将参考文献发布到文档中以备将来参考吗?那将算是我的答案。谢谢

1 个答案:

答案 0 :(得分:2)

这应该使您入门:

class Foo: Object {
    // other props
    @objc dynamic var id = ""
    let bars = List<Bar>()

    override static func primaryKey() -> String? {
        return "id"
    }
}

class Bar: Object {
    // other props
    @objc dynamic var id = ""
    let foo = LinkingObjects(fromType: Foo.self, property: "bars")

    override static func primaryKey() -> String? {
        return "id"
    }
}

let foo = Foo()
foo.id = "somethingUnique"
foo.someProp = "Mike"

let bar = Bar()
bar.id = "somethingUnique"
bar.someProp1 = "some value 1"

try! realm.write {
    realm.add(foo)
    realm.add(bar)
    foo.bars.append(bar)
}

let anotherBar = Bar()
anotherBar.id = "somethingUnique"
anotherBar.someProp1 = "some other value"
try! realm.write {
    realm.add(anotherBar)
    foo.bars.append(anotherBar)
}

其他地方:

var currentBars: List<Bar>()
if let findFoo = realm.object(ofType: Foo.self, forPrimaryKey: "someUniqueKey") {
    currentBars = findFoo.bars
    // to filter
    if let specificBar = currentBars.filter("id = %@", id) {
        // do something with specificBar
    }
}

要从酒吧获取foo:

if let bar = realm.object(ofType: Bar.self, forPrimaryKey: "theUniqueID") {
    if let foo = bar.foo.first {
        // you have your foo
    }
}

如果我正确理解了您的评论:

// already created foo
for nonRealmBar in nonRealmBars {
    // Note: you could also use realm.create
    let bar = Bar()
    bar.id = nonRealmBar.id
    bar.someProp = nonRealmBar.someProp
    // fill in other properties;
    try! realm.write {
        realm.add(bar)
        foo.bars.append(bar)
    }
}