如何在Sequelize中创造关系

时间:2016-03-06 17:18:19

标签: javascript node.js database sequelize.js

如何在表usersuser_friend之间创建正确的关系?我想向user_friends表发出加入请求。

var User = db.define('users', {
    userId: {
        primaryKey: true,
        autoIncrement: true,
        type: Sequelize.INTEGER,
        allowNull: false,
        field: 'user_id'
    },
    login: {
        type: Sequelize.STRING,
        isUnique: true
    }
}, {
    freezeTableName: true,
    classMethods: {
        associate: function (models) {
            User.hasMany(models.UserFriend, { as: 'Friends', foreignKey: 'user' });
        }
    }
});

var UserFriend = db.define('user_friend', {
    user: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'user_id'
        }
    },
    friend: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'user_id'
        }
    }
}, {
    freezeTableName: true,
    classMethods: {
        associate: function (models) {
            UserFriend.belongsTo(models.User, { foreignKey: 'user_id', targetKey: 'user' });
            UserFriend.belongsTo(models.User, { foreignKey: 'user_id', targetKey: 'friend' });
        }
    }
});

User.friends = function (id) {
    return UserFriend.findAll({
        where: { user: id },
        include: [
            { model: User }
        ]
    });
};

当我致电User.friends(1)时,它会抛出错误

Unhandled rejection Error: users is not associated to user_friend!

1 个答案:

答案 0 :(得分:0)

我的解决方案

var User = db.define('users', {
    userId: {
        primaryKey: true,
        autoIncrement: true,
        type: Sequelize.INTEGER,
        allowNull: false,
        field: 'user_id'
    },
    login: {
        type: Sequelize.STRING,
        isUnique: true
    }
});

var Friendship = db.define('friendship', {
    user: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'user_id'
        }
    },
    friend: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'user_id'
        }
    }
});

Friendship.belongsTo(User, { as: 'info', foreignKey: 'friend' });
User.belongsToMany(User, { as: 'friendship', through: Friendship, foreignKey: 'user', otherKey: 'friend' });
User.hasMany(Friendship, { as: 'friends', foreignKey: 'user' });

然后你可以得到这样的朋友

Friendship.findAll({
        where: { user: id },
        include: [{
            model: User,
            as: 'info'
        }]
    });