Skip to content

Instantly share code, notes, and snippets.

@tungd
Last active November 1, 2018 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tungd/d45ac1ac643334fcd26e57dd923faccf to your computer and use it in GitHub Desktop.
Save tungd/d45ac1ac643334fcd26e57dd923faccf to your computer and use it in GitHub Desktop.
Sequelize insert demo
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