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

问题描述 投票:0回答:1

我从关系方面来源于类似Ruby on 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看到一系列的barsbar.foo来获得foo

foobar尚未创建,因此不知道如何链接该批次立即保存。可能?怎么样?如果您要提供答案,是否可以发布对文档的引用以供将来参考?这对我来说算是一个答案。谢谢

swift realm swift4 swift4.2
1个回答
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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.