2015-12-30 85 views
3

我在SongsPeople之間有many-to-many。未指定加入模型,因爲它只有三列:主鍵song_idperson_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

我創建了一個測試項目,並得到了你的一樣(失敗)結果。看起來我們做得不對。你走得更遠了嗎? – Esteban

+0

@Esteban是的,我現在正在處理它。我一直在閱讀一些示例項目,bookshelf.js站點以這種方式鏈接到我的頭頂,並且這種方式似乎是錯誤的,因爲您必須首先'.save()'模型實例,然後是'.attach() 「這個協會,我可能是錯的。文檔很廣泛,但概念非常抽象。 –

+0

是的,他們缺乏IMO的好例子。另外,我首先嚐試了'.save()',它沒有什麼區別:( – Esteban

回答

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