我刚刚开始使用rethinkDB和thinky。我想问一下如何创建一个与现有模型具有n-n关系的模型的新实例。 例如,如果我有Pizzas和Toppings的模型。我已经创建了一个Pizza实例,如何创建一个顶部实例并将其链接到已经存在的披萨?
var Pizza = thinky.createModel("Pizza", {
name: type.string(),
size: type.string()
});
var Topping = thinky.createModel("Topping", {
name: type.string(),
});
Pizza.hasAndBelongsToMany(Topping, "toppings", "id", "id");
Topping.hasAndBelongsToMany(Pizza, "pizzas", "id", "id");
var pizza = new Pizza({name:"My pizza", size:"Large"});
var topping = new Topping({name:"Olive"});
如何保存顶部,以便与已经创建的披萨相关?
在docs中,对于1-n关系,他们执行以下操作:
topping.pizzas = pizza
topping.saveAll({pizza: true}).then(...);
在这种情况下,它将无法工作,因为topping.pizzas是一个对象数组而不仅仅是一个对象。
答案 0 :(得分:0)
The answer is pretty simple I found out:
var pizza = new Pizza({name:"My pizza", size:"Large"});
var topping = new Topping({name:"Olive"});
Topping.filter({name:Olive}).run().then(function (topping) {
if (topping.length > 0){
if (pizza.toppings == undefined){
pizza.toppings = []
}
pizza.toppings.push(topping[0]);
pizza.saveAll().then(...)
}
}
Pretty sure there are better ways to do it, but this works.