Sequelize findAll多对多的标准

时间:2016-07-03 14:43:49

标签: sql node.js orm associations sequelize.js

我有2个模型User和Item有很多关系,这里是定义:

User = sequelize.define('User', {
    name: {type: Sequelize.STRING}
  })
Item = sequelize.define('Item', {
        name: {
          type: Sequelize.STRING,
          allowNull: false
        }
      }
User.belongsToMany(models.Item, {
     as: 'items',
     through: 'UserItem'
})
Item.belongsToMany(models.User, {
     as: 'owners',
     through: 'UserItem'
})    

我的要求是:

Item.findAll({
    include: [{
      model: User,
      through: {
        where: {id: 2}
      }
    }]
  }).then(items => {
    log.debug(items)
  }).catch(err => {
    log.error(err)
  })

然后我有:Error: User is not associated to Item! 我也试试这个:

Item.findAll({
    where: {'owners.id': 2},
    include: Item.assocations.owners
  }).then(items => {
    debug(items)
  }).catch(err => {
    log.error(err)
  })

但现在我有Error: SQLITE_ERROR: no such column: Item.owners.id 有任何想法吗 ?

1 个答案:

答案 0 :(得分:0)

这是我的工作解决方案:

'use strict'
const Sequelize = require('Sequelize')

const sequelize = new Sequelize({
  host: 'localhost',
  dialect: 'sqlite',
  // SQLite only
  storage: 'database.sqlite'
})

const User = sequelize.define('user', {
  name: {
    type: Sequelize.STRING
  }
}, {
  freezeTableName: true // Model tableName will be the same as the model name
})

const Item = sequelize.define('item', {
  name: {
    type: Sequelize.STRING
  }
}, {
  freezeTableName: true // Model tableName will be the same as the model name
})

const UserItem = sequelize.define('useritem', {})

User.belongsToMany(Item, {
  as: 'items',
  through: 'useritem'
})
Item.belongsToMany(User, {
  as: 'owners',
  through: 'useritem'
})

Promise.all([
  User.sync({force: true}),
  Item.sync({force: true}),
  UserItem.sync({force: true})])
  .then(() => {
  return Promise.all([
    User.create({name: 'test'}),
    User.create({name: 'admin'}),
    Item.create({name: 'item1'}),
    Item.create({name: 'item2'})])
    .then(results => {
      return results[2].addOwner(results[0])
    }).then(() => {
      return Item.findAll({
        include: {model: User, as: 'owners', where:{
          'id': 1
        }}
      }).then(items => {
        console.log(items)
      })
})
}).catch(err => console.log(err))

as需要在include条款上,where也应添加include