Sequelize select 与同一实体的两个关系

Sequelize select with two relations to the same entity

我有 2 个表,ItemLegacy :

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('ItemLegacy', {
    id: {
      type: DataTypes.INTEGER(11).UNSIGNED,
      allowNull: false,
      primaryKey: true
    },
    parent: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      defaultValue: 0,
    },
    child: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      defaultValue: 0
    }
  }, {
    tableName: 'ItemLegacy',
    timestamps: false,
    underscored: false
  });
};

和项目:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('Item', {
    id: {
      type: DataTypes.INTEGER(11).UNSIGNED,
      allowNull: false,
      primaryKey: true
    },
    title: {
      type: DataTypes.STRING(500),
      allowNull: false,
      defaultValue: ''
    },
    code: {
      type: DataTypes.STRING(20),
      allowNull: true
    },
  }, {
    tableName: 'Item',
    timestamps: false,
    underscored: false
  });
};

我还定义了两个关系:

db.ccnLegacy.hasOne(db.ccn, { foreignKey: 'id', sourceKey: 'parent' })
db.ccnLegacy.hasOne(db.ccn, { foreignKey: 'id', sourceKey: 'child' })

我的问题是,我想使用 sequelize 创建一个 select 请求,其中每个字段 parentchild 都有一个关系。

我知道如何处理一个关系,但如何处理 2 个关系?

我的代码只有一个关系:

db.itemLegacy.findOne({
  raw: true,
  where: { child: idChild },
  include: [
    {
      model: db.item
    },
  ]
})

您只需为这两个关联指明别名并在查询中使用它们。其次,您使用 hasOne 而不是 belongTo,因为 belongTo 恰好用于 N:1 关系中从 N 到 1 的情况。

协会:

db.ccnLegacy.belongsTo(db.ccn, { foreignKey: 'parent', as: 'Parent' })
db.ccnLegacy.belongsTo(db.ccn, { foreignKey: 'child', as: 'Child' })

查询:

db.itemLegacy.findOne({
  raw: true,
  where: { child: idChild },
  include: [
    {
      model: db.item,
      as: 'Child'
    },
    {
      model: db.item,
      as: 'Parent'
    },
  ]
})