我有多对多关系的团体和受访者。 Group
和Respondent
实体的表每个都有一个整数主键(称为clusteredIndexId
的集群键)和一个UUID唯一键(全局唯一)记录标识符(称为id
),然后是业务数据的其他字段。我的RespondentGroup
映射表有一个整数主键clusteredIndexId
,然后有两个UUID列respondentId
,groupId
,它们是另两个表的外键。
我的数据库是PostgreSQL,我正在使用Knex来构建SQL查询,并将书架作为ORM。我可以通过书架在数据库中创建新的组和受访者。但我的代码在多对多映射表中未生成任何条目。有什么想法吗? (我是Node.js的新手,所以可能很明显。)
class Group extends bookshelf.Model {
get tableName() {
return 'Group';
}
static byId(id: string) { // TODO: how to make this a uuid?
return this.forge().query({where:{ id: id }}).fetch();
}
respondents() {
return this.belongsToMany(Respondent, 'RespondentGroup', 'groupId', 'respondentId');
}
}
class Respondent extends bookshelf.Model {
get tableName() {
return 'Respondent';
}
static byId(id: string) { // TODO: how to make this a uuid?
return this.forge().query({where:{ id: id }}).fetch();
}
groups() {
return this.belongsToMany(Group, 'RespondentGroup', 'respondentId', 'groupId');
}
}
// code from the Respondent controller
...
Group.default.byId(groupId)
.then((group: any) =>{
if(!group) {
resolve({code: 404, body: 'Group not found'});
} else {
var data = {
id: uuidv1(),
email: email
}
Respondent.default.forge(data).save(null, {method: 'insert'}).then(
function (group: any) {
respondent.groups().attach(group).then(() => resolve({code: 200, body: respondent}))
.catch((error: any) => resolve({code: 400, body: error}));
})
.catch((error: any) => resolve({code: 400, body: error}));
}
...