如何在 sequelize 中组合 2 个模型?
How can I combine 2 models in sequelize?
我有2个模型,每个模型有2个主键(langId,topicCode)。
如何将它们组合成 select 值?
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',
...
}
]
谢谢。
最好的祝福。
Sequelize 不支持关联中的复合键,因此您需要仅使用其中一个键来定义关联,并且 始终 指示 include
中的 on
选项带有两个字段条件的选项:
协会
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')
}
}]
})
我有2个模型,每个模型有2个主键(langId,topicCode)。
如何将它们组合成 select 值?
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',
...
}
]
谢谢。
最好的祝福。
Sequelize 不支持关联中的复合键,因此您需要仅使用其中一个键来定义关联,并且 始终 指示 include
中的 on
选项带有两个字段条件的选项:
协会
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')
}
}]
})