问题
Creating the following relationships
bookmark.belongsToMany(tag, {through: 'BookmarkTag'});
user.belongsToMany(bookmark, {through: 'UserBookmark'});
Will create two relationshiptables
BookmarkTag
|bookmarkId|tagId
UserBookmark
|bookmarkId|userId
i would like BookmarkTag to contain user id aswell so that i know which user added a tag to which bookmark
BookmarkTag
|bookmarkId|tagId|userId
is that possible through sequelize associations
fullcode
var bookmark = sequelize.define('Bookmark', {
name: Sequelize.STRING,
url: Sequelize.STRING
});
var tag = sequelize.define('Tag', {
value: Sequelize.STRING
});
var user = sequelize.define('User', {
email: Sequelize.STRING
});
bookmark.belongsToMany(tag, {through: 'BookmarkTag'});
user.belongsToMany(bookmark, {through: 'UserBookmark'});
sequelize.sync();
回答1:
If you define the BookmarkTag table explicitly you can add extra attributes to it:
BookmarkTag = sequelize.define('BookmarkTag', {
userId: Sequelize.INTEGER
});
bookmark.belongsToMany(tag, {through: BookmarkTag});
Notice that we are passing a reference to the BookmarkTag model, not a string here.
To set a userid on the tag, you pass an extra object when doing addTag
Bookmark.addTag(tag, { userId: 42 });
来源:https://stackoverflow.com/questions/29099956/three-way-relationship