我想用原始json数据
创建持久模型var data = {
id: 77
name: "Fred"
parent_id: 887
parent: {
id: 887,
name: "Ted"
things: [
{ id:991, name: "some", parent_id: 887 },
{ id:992, name: "another", parent_id: 887 },
{ id:993, name: "cu", parent_id: 887 }
]
}
}
我简化了数据(我在模型中有很多关联,在关联的子模型中有一些关联)
我尝试使用Model.create(数据,选项) with options.include:[SubModel]但它不起作用。它只在主模型的db中创建一行 并忽略SubModel
答案 0 :(得分:0)
据我所知,基于现有数据创建模型实例的唯一方法是使用build函数。但是使用相关的模型实例创建模型实例也有些棘手。
所以解决方案(基于您的JSON数据)更像
const thingsData = [
{ id:991, name: "some", parent_id: 887 },
{ id:992, name: "another", parent_id: 887 },
{ id:993, name: "cu", parent_id: 887 }
]
const things = ThingsModel.build(thingsData) // this will be an array of ThingsModel instance
const parentData = {
id: 887,
name: "Ted"
}
const parent = ParentModel.build(parentData)
// manually injecting the things instances
parent.dataValues.things = things
const personData = {
id: 77,
name: "Fred",
parent_id: 887
}
const person = PersonModel.build(data)
person.dataValues.parent = parent