woolywhale woolywhale - 18 days ago 6
Javascript Question

Sequelize include an attribute from junction table

I'm building a shop, where in the database i have orders and items. Here's the code for the models:

Item:

var Sequelize = require('sequelize')
var sequelize = require('./sequelize')
var Item = sequelize.define('item', {
image: {
type: Sequelize.STRING,
allowNull: false
},
itemName: {
type: Sequelize.STRING,
allowNull: false,
field: 'item_name'
},
price: {
type: Sequelize.INTEGER,
allowNull: false
}
})

module.exports = Item


Order:

var Sequelize = require('sequelize')
var sequelize = require('./sequelize')
var Order = sequelize.define('order', {
orderNumber: {
primaryKey: true,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4
},
shop: {
type: Sequelize.INTEGER
},
location: {
type: Sequelize.STRING
}
})

module.exports = Order


They are related through belongs to many:

Item.belongsToMany(Order, {through: OrderItem})
Order.belongsToMany(Item, {through: OrderItem})


The OrderItem has an additional field, 'count', which i need to return:

var Sequelize = require('sequelize')
var sequelize = require('./sequelize')

var OrderItem = sequelize.define('OrderItem', {
count: Sequelize.INTEGER
})

module.exports = OrderItem


However, when i try to include the OrderItem model, it doesn't work. No errors, nothing. The query just doesn't return:

Order.findAll({
where: {
userId: userId
},
include: [{
model: Item,
include: [OrderItem]
}]
}).then(orders => {
console.log(orders)
res.status(200).json(orders)
})


How to get what i need from sequeilize?

Answer

You may try something like this:

  Order.findAll({
      where: {
        userId: userId
      },
      include: [{ model: Item, 
        as:'item', 
        through:{attributes:['count']} // this may not be needed
      }]
  }).then(orders => {
    console.log(orders)
    res.status(200).json(orders)
  })

Also, your models must have a right naming strategy. E.g. :

Item - must have itemId field instead of itemNumber, Order - must have orderId as primary field

OrderItem's structure:

var OrderItem = sequelize.define('OrderItem', {
  orderId: Sequelize.INTEGER,
  itemId: Sequelize.INTEGER,
  count: Sequelize.INTEGER
})

Another one is to use direct names of related fields and models when you use belongsToMany()

More here: http://docs.sequelizejs.com/en/latest/docs/associations/