序列化-属于使用targetKey

时间:2019-05-10 02:41:22

标签: sequelize.js

我正在尝试将交叉引用数据的引用添加到我的过渡表之一。但是看起来Sequelize生成的查询是不正确的。

以下是我正在使用的表结构:

付款类型:

enter image description here

Payment_Dtls:

enter image description here

以下是我的Sequelize模型:

付款类型:

const Sequelize = require('sequelize');
const connection = require('../middleware/sql-connection');

const PaymentType = connection.define('PAYMENT_TYPE', {
    'ID': { type: Sequelize.BIGINT, primaryKey: true },
    'CD': { type: Sequelize.STRING, allowNulls: false }
});

module.exports = PaymentType;

付款明细:

const Sequelize = require('sequelize');
const connection = require('../middleware/sql-connection');
const PaymentType = require('./payment-type');

const PaymentDetails = connection.define('PAYMENT_DTLS', {
    'ID': { type: Sequelize.BIGINT, primaryKey: true },
    'PAYMENT_TYPE_ID': { type: Sequelize.BIGINT, allowNull: false },
    'AMOUNT': { type: Sequelize.DECIMAL, allowNull: false },
    'USR_ID': { type: Sequelize.BIGINT, allowNull: false },
    'PAYMENT_DT': { type: Sequelize.DATE, allowNull: false },
    'STS': Sequelize.STRING
});

PaymentDetails.hasOne(PaymentType);
module.exports = PaymentDetails;

当我尝试在我的PaymentDetails查询中包括PaymentType时,生成的SQL似乎不正确。我的findall方法:

exports.payment_details__by_current_user = (req, res, next) => {
    PaymentDetails.findAll({
        include: [{ model: PaymentType }]
    })
        .then(requests => {return res.status(200).json(requests);})
        .catch(err => {return res.status(500).json({ message: err });});
};

以下是生成的SQL查询:

SELECT ... FROM [PAYMENT_DTLS] AS [PAYMENT_DTLS] LEFT OUTER JOIN [PAYMENT_TYPE] AS [PAYMENT_TYPE] 
ON [PAYMENT_DTLS].[ID] = [PAYMENT_TYPE].[PAYMENTDTLID];

我希望它在哪里生成:

SELECT ... FROM [PAYMENT_DTLS] AS [PAYMENT_DTLS] LEFT OUTER JOIN [PAYMENT_TYPE] AS [PAYMENT_TYPE] 
ON [PAYMENT_DTLS].[PAYMENT_TYPE_ID] = [PAYMENT_TYPE].[ID];

我尝试了以下所有关联,但似乎无济于事:

选项1:

PaymentDetails.hasOne(PaymentType, { foreignKey: 'PAYMENT_TYPE_ID' });

选项2:

PaymentType.belongsTo(PaymentDetails, { foreignKey: 'PAYMENT_TYPE_ID' });
PaymentDetails.hasOne(PaymentType,{foreignKey:'ID'});

选项3:

PaymentType.belongsTo(PaymentDetails, { foreignKey: 'PAYMENT_TYPE_ID' });
PaymentDetails.hasOne(PaymentType, { foreignKey: 'ID', targetKey: 'PAYMENT_TYPE_ID' });

1 个答案:

答案 0 :(得分:0)

我认为belongsTo()应该可以满足您的需求:

PaymentDetails.belongsTo(PaymentType, {foreignKey: 'PAYMENT_TYPE_ID'});

直观上讲,hasOne()似乎更合适……但是尝试使hasOne()使用自定义键时遇到了很多麻烦。