我在many-to-many
和Songs
之间有一个People
。未指定连接模型,因为它只有三列:主键song_id
和person_id
。
书架定义:
//Song
Bookshelf.model("Song", {
tableName: "songs",
people: function() {
return this.belongsToMany("Person", "people_songs");
}
});
//Person
Bookshelf.model("Person", {
tableName: "people",
songs: function() {
return this.belongsToMany("Song", "people_songs");
}
});
鉴于歌曲ID和人物ID,我想在连接表中添加一行。 Attach似乎是在模型实例上使用的正确方法,所以在控制器中我可以做...
Models
.Song
.forge()
.where({id: 1})
.people()
.attach( new Models.Person({id: 1}) )
.then(function(instance) {
res.send();
});
当我查询行时,song_id
为空? (我应该列notNullable()
列,但除此之外......
我也试过updatePivot
这样:
Models
.Song
.forge()
.where({id: 1})
.people()
.updatePivot({song_id: 1, person_id: 1})
.then(function(instance) {
res.send();
});
但是,这甚至没有在连接表中插入任何东西。但是,如果我注销updatePivot
承诺的结果,我会得到这个:
relatedData: {
targetTableName: "songs",
targetIdAttribute: "id",
joinTableName: "people_songs",
foreignKey: "song_id"
otherKey: undefined,
parentId: undefined,
parentTableName: "people",
parentIdAttribute: "id",
parentFk: undefined
}
答案 0 :(得分:1)
在repo issue中找到解决方案。
//get the model
Models
.Song
.forge({id: 12})
//but I have no idea why save is being used here instead of fetch
.save()
.then(function(model) {
//get the other model you want to add to the join table
return Models
.Person
.forge({id: 56})
.save()
.then(function(target) {
//need to send both references down the promise chain
return {target: target, model: model};
});
})
.then(function(references) {
return references
.model
//get the belongsToMany relation specified in your Model definition, it returns a collection
.people()
//attach the target to the collection, not the model instance
.attach(references.target);
})
.then(function(relation) {
res.send();
})
结果是
people_songs
id | person_id | song_id
___________________________
3 | 56 | 12