如何使用Sequelize MySQL添加外键

时间:2019-02-05 20:13:12

标签: mysql node.js sequelize.js

“我有2个表“ Users”和“ Profile_personals”。如何使用我的Users表中的“ user_id”主键将外键约束添加到我的个人资料中?我正在使用node.js,sequelize mysql。

Users(parent Table):

    const Sequelize = require('sequelize')
    const db = require("../database/db.js")

    module.exports = db.sequelize.define(
        "users", 
        {
            user_id: {
                type: Sequelize.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            email: {
                type: Sequelize.STRING
            },
            password: {
                type: Sequelize.STRING
            }
        },    
        {
            timestamps: false
        }
    )


    Personals(Child Table):


    const Sequelize = require('sequelize')
    const db = require("../database/db.js")

    module.exports = db.sequelize.define(
        'profile_personals', 
        {
            id: {
                type: Sequelize.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            biography: {
                type: Sequelize.STRING
            }       
        },    
        {
            timestamps: false
        }
    )

1 个答案:

答案 0 :(得分:0)

这样做,我希望它就是您要的。

module.exports = db.sequelize.define(
    'profile_personals',
    {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        biography: {
            type: Sequelize.STRING
        },
        // It is possible to create foreign keys:
        user_id: {
            type: Sequelize.INTEGER,

            references: {
                // This is a reference to another model
                model: Users,

                // This is the column name of the referenced model
                key: 'user_id'
            }
        }
    },
    {
        timestamps: false
    }
);