3
我在Songs
和People
之間有many-to-many
。未指定加入模型,因爲它只有三列:主鍵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
}
我創建了一個測試項目,並得到了你的一樣(失敗)結果。看起來我們做得不對。你走得更遠了嗎? – Esteban
@Esteban是的,我現在正在處理它。我一直在閱讀一些示例項目,bookshelf.js站點以這種方式鏈接到我的頭頂,並且這種方式似乎是錯誤的,因爲您必須首先'.save()'模型實例,然後是'.attach() 「這個協會,我可能是錯的。文檔很廣泛,但概念非常抽象。 –
是的,他們缺乏IMO的好例子。另外,我首先嚐試了'.save()',它沒有什麼區別:( – Esteban