我有2类A和B,3个表A,B和AB
A.belongsToMany(B,as:'Bs', through: models.AB)
B.belongsToMany(A,as:'As', through: models.AB)
到现在为止,协会正在IM能够与B到去取包括和周围的其他方式。
当即时试图创建A,我发送的JSON包括所选择的B值。我的JSON:
{
"name" : "A"
"Bs": [
{"id_B" : 1},
{"id_B" :2},
{"id_B" :3}
]
}
我的代码中插入行是:
A= await models.A.build(req.body,
{
transaction:transaction,
include:[
{ as:'Bs',required:true,model:models.B},
]
}
)
我所期望的结果是是sequelize创造与提供的ID和新创建的ID_A AB表里面的行,而是它试图创建B表内的行ID_B因为其它属性不能为空的失败。
我已经搜索相当长一段时间,并试图多种解决方案,我明白,我能有两个步骤来做到这一点:
1)创建一个
2)A.addB()
题:
1)是否有可能以一步做呢?
2)我在做什么毛病我的JSON或它是不可能的?
使用include
create
/ build
意味着我们要插入记录到包括表。因此,以下包括表示记录应被插入到表B:
include:[
{ as:'Bs',required:true,model:models.B},
]
由于B值已经在数据库中存在,值应仅加入A
和AB
需要的是这样的是:
A
和AB
表之间的关联。AB
/ create
语句中使用build
。该代码应该是这样的:
A.belongsToMany(B, { through: AB, as: 'Bs', foreignKey: 'id_A' }); // Not relevant for this use case
B.belongsToMany(A, { through: AB, as: 'As', foreignKey: 'id_B' }); // Not relevant for this use case
A.hasMany(AB, { as: 'ABs', foreignKey: 'id_A'} );
const a = await A.create({
id: 1,
ABs: [{ id_B: 22 }]
}, {
include: [{
model: AB,
as: 'ABs'
}]
});