Sequelize JS-在联接中选择On子句

时间:2019-05-10 17:46:34

标签: javascript node.js sequelize.js

我想知道如何在联接中选择ON子句。我有两个表,packagesuserspackage表具有两个字段/列(owner_id,helper_id),它们是同一表users的外键。我想要一个可以加入packages.owner_id = users.idpackages.helper_id = users.id的地方。这是我所拥有的:

models.Packages.findAll({
    where: (!package_id ? { owner_id } : { owner_id, id: { [Op.lt]: package_id } }),
    include: [{
      model: models.Users,
      attributes: { exclude: ['password'] },
      where: ['helper_id = id']
    }],
    limit: 5,
    order: [["id","DESC"]]
  })

和另一个

models.Packages.findAll({
    where: (!package_id ? { owner_id } : { owner_id, id: { [Op.lt]: package_id } }),
    include: [{
      model: models.Users,
      attributes: { exclude: ['password'] },
      where: ['owner_id = id']
    }],
    limit: 5,
    order: [["id","DESC"]]
  })

但是我得到这个错误:

Unhandled rejection Error: Support for literal replacements in the `where` object has been removed

请帮助?

2 个答案:

答案 0 :(得分:1)

您的代码应为:

models.Packages.findAll({
    where: (!package_id ? { owner_id } : { owner_id, id: { [Op.lt]: package_id } }),
    include: [{
      model: models.Users,
      attributes: { exclude: ['password'] },
      where: { 'helper_id': Sequelize.col('Users.id') },
    limit: 5,
    order: [["id","DESC"]]
  })

有关更多信息,请参见Sequelize文档,网址为: sequelizejs Relations / Associations

答案 1 :(得分:1)

我喜欢Shahar Hadas的答案,但是我确实找到了解决方法。

基本上,我必须定义一个具有特定别名的关系/关联(请注意as属性):

models.Users.hasMany(models.Packages, { foreignKey: 'owner_id', sourceKey: 'id' });
models.Users.hasMany(models.Packages, { foreignKey: 'helper_id', sourceKey: 'id' });
models.Packages.belongsTo(models.Users, { as: 'owner', foreignKey: 'owner_id', targetKey: 'id' });
models.Packages.belongsTo(models.Users, { as: 'helper', foreignKey: 'helper_id', targetKey: 'id' });

然后,当我查询时,我可以选择我想要的别名:

models.Packages.findAll({
    where: (!package_id ? { owner_id } : { owner_id, id: { [Op.lt]: package_id } }),
    include: [{
      model: models.Users,
      as: 'owner',
      attributes: { exclude: ['password'] }
    }],
    limit: 5,
    order: [["id","DESC"]]
  })

models.Packages.findAll({
    where: (!package_id ? { owner_id } : { owner_id, id: { [Op.lt]: package_id } }),
    include: [{
      model: models.Users,
      as: 'helper',
      attributes: { exclude: ['password'] }
    }],
    limit: 5,
    order: [["id","DESC"]]
  })