モデルデータ
//レシピモデル
class Recipe: Object {
@objc dynamic var name = ""
@objc dynamic var category = ""
@objc dynamic var country = ""
@objc dynamic var season = ""
let ingredients = List() //レシピと材料は1対多の関係
override static func primaryKey() -> String? {
return "name"
}
}
//材料モデル
class Ingredient: Object {
@objc dynamic var name = ""
let recipes = LinkingObjects(fromType: Recipe.self, property: "ingredients")
}
モデルデータの格納、検索、表示
do {
//トマトパスタ、カツ丼、カレーの3つのレシピのモデルを作成
let realm = try Realm()
let dictionary1: [String: Any] =
["name": "トマトパスタ",
"category": "パスタ",
"country" : "イタリア",
"season" : "春",
"ingredients":[["name": "トマト"],["name": "にんにく"]]
]
let dictionary2: [String: Any] =
["name": "カツ丼",
"category": "丼",
"country" : "日本",
"season" : "夏",
"ingredients":[["name": "たまねぎ"],["name": "卵"]]
]
let dictionary3: [String: Any] =
["name": "カレー",
"category": "カレー",
"country" : "日本",
"season" : "夏",
"ingredients":[["name": "たまねぎ"],["name": "にんじん"],["name":"じゃがいも"]]
]
let recipe1 = Recipe(value: dictionary1)
let recipe2 = Recipe(value: dictionary2)
let recipe3 = Recipe(value: dictionary3)
try! realm.write {
realm.deleteAll() //既に保存済のモデルを一旦削除
realm.add(recipe1)//レシピモデルの保存
realm.add(recipe2)//レシピモデルの保存
realm.add(recipe3)//レシピモデルの保存
//材料にたまねぎを使用するレシピモデルを取得する
var objects: Results<Recipe>
objects = realm.objects(Recipe.self).filter("SUBQUERY(ingredients, $ingredient, $ingredient.name = %@).@count >= 1","たまねぎ")
print("objectsの中",objects)
}
} catch {
print("エラー")
}
出力結果
objectsの中 Results<0x10461f0e0> ( [0] Recipe { name = カツ丼; category = 丼; country = 日本; season = 夏; ingredients = List <0x280756760> ( [0] Ingredient { name = たまねぎ; }, [1] Ingredient { name = 卵; } ); }, [1] Recipe { name = カレー; category = カレー; country = 日本; season = 夏; ingredients = List <0x280756880> ( [0] Ingredient { name = たまねぎ; }, [1] Ingredient { name = にんじん; }, [2] Ingredient { name = じゃがいも; } ); } )
0 件のコメント:
コメントを投稿