将行插入连接 table?

Inserting row into join table?

我在 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,我想向联接中添加一行 table。 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();
    });

但是那甚至没有在连接中插入任何东西 table。但是,如果我注销 updatePivot 承诺的结果,我会得到这个:

relatedData: {
    targetTableName: "songs",
    targetIdAttribute: "id",
    joinTableName: "people_songs",
    foreignKey: "song_id"
    otherKey: undefined,
    parentId: undefined,
    parentTableName: "people",
    parentIdAttribute: "id",
    parentFk: undefined
}

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