三方关系

时间:2015-03-17 13:10:02

标签: sequelize.js

创建以下关系

bookmark.belongsToMany(tag, {through: 'BookmarkTag'}); user.belongsToMany(bookmark, {through: 'UserBookmark'});

将创建两个关系表

BookmarkTag |bookmarkId|tagId

UserBookmark |bookmarkId|userId

我希望BookmarkTag包含用户ID以便我知道哪个用户添加了一个标签到哪个书签

BookmarkTag

| bookmarkId | TAGID |用户id

可以通过续集关联

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 个答案:

答案 0 :(得分:1)

如果明确定义BookmarkTag表,则可以向其添加额外属性:

BookmarkTag = sequelize.define('BookmarkTag', {
    userId: Sequelize.INTEGER
});

bookmark.belongsToMany(tag, {through: BookmarkTag});

请注意,我们正在传递对BookmarkTag模型的引用,而不是此处的字符串。

要在标记上设置用户标识,请在执行addTag

时传递额外的对象
Bookmark.addTag(tag, { userId: 42 });