Last active
          November 1, 2018 07:59 
        
      - 
      
 - 
        
Save tungd/d45ac1ac643334fcd26e57dd923faccf to your computer and use it in GitHub Desktop.  
    Sequelize insert demo
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | const Sequelize = require('sequelize') | |
| const sequelize = new Sequelize({ | |
| dialect: 'sqlite', | |
| storage: 'db.sqlite3' | |
| }) | |
| const Product = sequelize.define('product', { | |
| name: Sequelize.STRING | |
| }) | |
| const OrderItem = sequelize.define('order_item', { | |
| quantity: Sequelize.INTEGER | |
| }) | |
| OrderItem.Product = OrderItem.belongsTo(Product) | |
| const Address = sequelize.define('address', { | |
| city: Sequelize.STRING, | |
| }) | |
| const Order = sequelize.define('order', { | |
| }) | |
| Order.OrderItem = Order.hasMany(OrderItem) | |
| Order.hasOne(Address) | |
| Order.Product = Order.belongsToMany(Product, { through: OrderItem }) | |
| Product.Order = Product.belongsToMany(Order, { through: OrderItem }) | |
| const main = async () => { | |
| await sequelize.authenticate() | |
| await sequelize.sync({ force: true }) | |
| await Product.create({ | |
| name: 'Product 1' | |
| }) | |
| // Your case | |
| const product = await Product.findByPk(1) | |
| const order = await Order.create({ | |
| order_items: [{ | |
| productId: product.id, | |
| quantity: 2, | |
| }], | |
| address: { | |
| city: 'Ha Noi' | |
| } | |
| }, { | |
| include: [OrderItem, Address] | |
| }) | |
| // The case you asked | |
| const order2 = await Order.create({ | |
| order_items: [{ | |
| product: { | |
| name: 'Product 2' | |
| }, | |
| quantity: 2, | |
| }], | |
| address: { | |
| city: 'Ha Noi' | |
| } | |
| }, { | |
| include: [{ | |
| association: Order.OrderItem, | |
| include: [OrderItem.Product] | |
| }, Address] | |
| }) | |
| // BelongsToMany | |
| const order3 = await Order.create({ | |
| products: [{ | |
| name: 'Product 2' | |
| }], | |
| address: { | |
| city: 'Ha Noi' | |
| } | |
| }, { | |
| include: [Product, Address] | |
| }) | |
| } | |
| main() | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment