【问题标题】:How to create model instance with associations in sequelizejs?如何在 sequelizejs 中创建具有关联的模型实例?
【发布时间】:2014-07-10 17:41:59
【问题描述】:

我想通过原始 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(data, options) 使用 options.include: [SubModel] 但它不起作用。它只在主模型的数据库中创建行 并忽略子模型

【问题讨论】:

    标签: node.js postgresql orm sequelize.js


    【解决方案1】:

    据我所知,基于现有数据创建模型实例的唯一方法是使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-13
      • 2016-04-02
      • 2020-10-11
      • 2017-07-19
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 2018-10-28
      相关资源
      最近更新 更多