我有 2 個模型,每個模型有 2 個主鍵(langId,topicCode)。如何結合它們來選擇值?
const field_A = {langId: {type:DataTypes.STRING, primaryKey: true}, topicCode: {type:DataTypes.STRING, primaryKey: true}, data:{type:DataTypes.STRING}}
const field_B = {langId: {type:DataTypes.STRING, primaryKey: true}, topicCode: {type:DataTypes.STRING, primaryKey: true}, storage:{type:DataTypes.STRING}}
Model_A.init(field_A, { timestamps:false, sequelize });
Model_B.init(field_B, { timestamps:false, sequelize });
如何通過使用模型之間的 sequelize 關聯來執行以下操作?
SELECT * from Model_A, Model_B where Model_A.langId = Model_B.langId and Model_A.topicCode = Model_B.topicCode
[
{
langId: 'xx',
topicCode: 'yy',
data: 'zz',
storage: 'pp',
},
{
langId: 'gg',
...
}
]
謝謝你。
最好的祝福。
uj5u.com熱心網友回復:
Sequelize 不支持關聯中的復合鍵,因此您只需定義與其中一個鍵的關聯,并始終在選項中為兩個欄位的條件指明on選項:include
協會
modelA.belongsTo(modelB, { foreignKey: 'langId' });
詢問
const modelAList = await ModelA.findAll({
include: [{
model: ModelB,
on: {
'$ModelA.langId$': Sequelize.col('ModelB.langId'),
'$ModelA.topicCode$': Sequelize.col('ModelB.topicCode')
}
}]
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/428882.html
