我从我的续集中获得了下表设置。
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",
}
}
我试图以这种方式使用关联设置,但是始终与一个字段的续集相关,我希望它为两个字段显示。accountIdFrom
和acountIdTo
。
预期的回报应该是这样的,但是它不起作用:
{
"id": 2,
"value": "10.00",
"accountIdFrom": 2,
"accountIdTo": 1,
"AccountFrom": {
"id": 2,
"name": "Bank Two",
},
"AccountTo": {
"id": 1,
"name": "Bank One",
}
}
您必须使用as:
而不是foreignKey:
Transfers.belongsTo(Accounts, { as: 'accountFrom', onDelete: 'cascade', onUpdate: 'no action' });
Transfers.belongsTo(Accounts, { as: 'accountTo', onDelete: 'cascade', onUpdate: 'no action' });
这将为您的Accounts
模型提供列accountFromId
和accountToId
。因此,当您需要包含这样的模型时,您将这样做:
Transfers.find( {
where: {},
include: [{
model: db.Accounts,
as: 'accountFrom'
},{
model: db.Accounts,
as: 'accountTo'
}]
})
我在@ellebkey的帮助下找到了解决方案。关注Bellow代码。
create-transfers.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;
};
控制器/Transfers.js
const data = await Transfers.find({
where: {},
include: [{
model: database.Accounts,
as: 'AccountFrom',
}, {
model: database.Accounts,
as: 'AccountTo',
}],
});