在 Realm Swift 中查询一对多关系中的项目

Querying items in a one-to-many relationship in Realm Swift

如何根据以下代码查询列表中的所有项目?

我想要的是能够说,给我所有属于 List 1 等的物品

购物清单模型

import Foundation
import RealmSwift

class ShoppingList: Object{
    dynamic var listName = ""
    var itemList = List<Item>()
}

物品型号

import Foundation
import RealmSwift

class Item:Object {
    dynamic var productName: String = ""
}

所有购物清单的输出(realm.objects(ShoppingList.self)

Lists: Results<ShoppingList> (
    [0] ShoppingList {
        listName = List 1;
        itemList = RLMArray <0x6180000feb80> (
            [0] Item {
                productName = Jitomates;
            },
            [1] Item {
                productName = Grapes;
            },
            [2] Item {
                productName = Oranges;
            }
        );
    },
    [1] ShoppingList {
        listName = List 2;
        itemList = RLMArray <0x6180000fec80> (
            [0] Item {
                productName = Tomatoes;
            },
            [1] Item {
                productName = Grapes;
            },
            [2] Item {
                productName = Oranges;
            },
            [3] Item {
                productName = Green Peppers;
            },
            [4] Item {
                productName = Apples;
            }
        );
    }
)

编辑:

下面的查询与我要查找的内容很接近,只是它输出一个 Results,而我只需要一个 List,其中包含列表 2

中的所有项目

let itemsFromList2 = realm.objects(ShoppingList.self).filter("listName = 'List 2' ")

Items: Results<ShoppingList> (
    [0] ShoppingList {
        listName = List 2;
        itemList = RLMArray <0x6000000e3500> (
            [0] Item {
                productName = Tomatoes;
            },
            [1] Item {
                productName = Grapes;
            },
            [2] Item {
                productName = Oranges;
            },
            [3] Item {
                productName = Green Pappers;
            },
            [4] Item {
                productName = Apples;
            }
        );
    }
)

您从领域获取 Results,然后从 Results 获取领域对象。 希望下面的代码对你有帮助。

let itemsFromList2 = realm.objects(ShoppingList.self).filter("listName = 'List 2'")
// Results acts like an Array
let shoppingList2 = itemsFromList2.first!
// itemList is what you need I think
let itemList = shoppingList2.itemList