如何在Sequelize.js中将两个表关联到第三个?

时间:2016-04-22 09:38:15

标签: mysql node.js sequelize.js

我有两个表:sitesusers通过表links与自定义字段JOIN links ON links.links.Sourceindex = sites.id AND links.Sourcetable = 'SITES' AND links.Contactindex = 'USER_ID'关联,是否可以在Sequelize中进行?

2 个答案:

答案 0 :(得分:0)

当然可以。如果不了解有关您尝试执行的查询的更多详细信息,可能这些模型文件可以正常工作。

users.js

module.exports = (sequelize, DataTypes) => sequelize.define('users', {
    id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    username: {
        type: DataTypes.STRING,
        allowNull: false
    },
    first_name: {
        type: DataTypes.STRING,
        allowNull: false
    },
    last_name: {
        type: DataTypes.STRING,
        allowNull: false
    }
}, {
    tableName: 'users',
    freezeTableName: true,
    classMethods: {
        associate: models => {
            models.users.belongsToMany(models.sites, {
                through: 'links',
                foreignKey: 'contact_index'
            });
        }
    }
});

sites.js

module.exports = (sequelize, DataTypes) => sequelize.define('sites', {
    id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        primaryKey: true,
        autoIncrement: true
    },
    url: {
        type: DataTypes.STRING,
        allowNull: true
    }
}, {
    tableName: 'sites',
    freezeTableName: true,
    classMethods: {
        associate: models => {
            models.sites.belongsToMany(models.users, {
                through: 'links',
                foreignKey: 'source_index'
            });
        }
    }
});

答案 1 :(得分:0)