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

Using RealmSwift to save an one-to-many relationship object

我来自 Ruby 在关系方面类似于 Rails 的数据结构。

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

通过 RealmSwift 文档,我想到了这个,我认为:

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.bars看到bars的数组,bar.foo得到foo

foobar 还没有创建所以不知道如何链接该批次以立即保存。可能的?如何?如果您要提供答案,您能否 post 参考文档以供将来参考?这对我来说算是一个答案。谢谢

这应该让你开始:

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
    }
}

从 bar 获取 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)
    }
}