Three way relationship

烂漫一生 提交于 2019-12-11 11:12:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!