Sequelize:如何将表中的两个字段与另一个表相关联

时间:2018-04-23 18:29:03

标签: javascript node.js sequelize.js

我的续集中有以下表格设置。

const Accounts = sequelize.define('Accounts', {
  name: DataTypes.STRING,
});

const Transfers = sequelize.define('Transfers', {
  value: {
    type: DataTypes.DECIMAL(10, 2),
    defaultValue: 0,
  },
  accountIdFrom: DataTypes.INTEGER,
  accountIdTo: DataTypes.INTEGER,
});

Transfers.belongsTo(Accounts, { foreignKey: 'accountIdFrom' });
Transfers.belongsTo(Accounts, { foreignKey: 'accountIdTo' });

const data = await Transfers.findAll({
  include: [{ model: Accounts }]
});

返回:

{
  "id": 1,
  "value": "10.00",
  "accountIdFrom": 1,
  "accountIdTo": 2,
  "Account": {
    "id": 2,
    "name": "Banco Neon",
  }
}

我尝试以这种方式使用关联设置,但是sequelize总是只关联一个字段,我希望它显示两个字段。 accountIdFromacountIdTo

预期的回报应该是这样的,但是,它不起作用:

{
  "id": 2,
  "value": "10.00",
  "accountIdFrom": 2,
  "accountIdTo": 1,
  "AccountFrom": {
    "id": 2,
    "name": "Bank Two",
  },
  "AccountTo": {
    "id": 1,
    "name": "Bank One",
  }
}

2 个答案:

答案 0 :(得分:0)

您必须使用as:代替foreignKey:

Transfers.belongsTo(Accounts, { as: 'accountFrom', onDelete: 'cascade', onUpdate: 'no action' });
Transfers.belongsTo(Accounts, { as: 'accountTo', onDelete: 'cascade', onUpdate: 'no action' });

这会在Accounts模型上为您提供accountFromIdaccountToId列。因此,当您需要包含模型时,您将会这样做:

Transfers.find( {
  where: {},
  include: [{
    model: db.Accounts,
    as: 'accountFrom'
  },{
    model: db.Accounts,
    as: 'accountTo'
  }]
})

答案 1 :(得分:0)

我在@Ellebkey的帮助下找到了解决方案。请遵循以下代码。

create-transferss.js

module.exports = {
  up: (queryInterface, Sequelize) => (
    queryInterface.createTable('Transfers', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      value: {
        type: Sequelize.DECIMAL(10, 2),
        defaultValue: 0,
      },
      accountFromId: {
        type: Sequelize.INTEGER,
      },
      accountToId: {
        type: Sequelize.INTEGER,
      },
    })
      .then(() => (
        queryInterface.addConstraint('Transfers', ['accountFromId'], {
          type: 'foreign key',
          name: 'fk_transfers_account_from',
          references: { // Required field
            table: 'Accounts',
            field: 'id',
          },
          onDelete: 'cascade',
          onUpdate: 'no action',
        })
      ))
      .then(() => (
        queryInterface.addConstraint('Transfers', ['accountToId'], {
          type: 'foreign key',
          name: 'fk_transfers_account_to',
          references: { // Required field
            table: 'Accounts',
            field: 'id',
          },
          onDelete: 'cascade',
          onUpdate: 'no action',
        })
      ))
  ),
  down: queryInterface => queryInterface.dropTable('Transfers'),
};

model / transfers.js

module.exports = (sequelize, DataTypes) => {
    const Transfers = sequelize.define('Transfers', {
        value: {
            type: DataTypes.DECIMAL(10, 2),
            defaultValue: 0,
        },
        accountFromId: DataTypes.INTEGER,
        accountToId: DataTypes.INTEGER,
    }, {});
    Transfers.associate = ({ Accounts }) => {
        Transfers.belongsTo(Accounts, { as: 'AccountFrom' });
        Transfers.belongsTo(Accounts, { as: 'AccountTo' });
    };
    return Transfers;
};

controller / transfers.js

const data = await Transfers.find({
    where: {},
    include: [{
        model: database.Accounts,
        as: 'AccountFrom',
    }, {
        model: database.Accounts,
        as: 'AccountTo',
    }],
});