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

标签 swift realm swift4 swift4.2

在关系方面,我来自类似 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 的数组来获取

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

最佳答案

这应该让你开始:

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

关于swift - 使用 RealmSwift 保存一对多关系对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54725688/

相关文章:

swift - 核心数据处理集

swift - 如何使用 swift 在 uicollectionview 中添加投影?

java - RealmMigration 删除了我 Realm 中的所有数据

swift - VNDetectFaceRectangles请求检测人脸

ios - swift 4 : prepare(for segue:) being called after viewDidLoad

iOS 在 Storyboard上添加设计时文本

swift - 另一个类中的委托(delegate)

java - 按字符串数组字段过滤 Realm 结果

swift - Realm Swift 代码用于查询/添加具有关系的 3 个深表中的记录

ios - 为什么UILabel TapGesture 只能在标签初始化后工作?