【问题标题】:How to add foreign key using sequelize mysql如何使用 sequelize mysql 添加外键
【发布时间】:2019-06-29 17:43:34
【问题描述】:

“我有 2 个表“Users”和“Profile_personals”。如何使用我的 Users 表中的“user_id”主表向我的个人资料个人添加外键约束?我正在使用 node.js,续集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
        }
    )

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    这样做,我希望它是你正在寻找的。​​p>

    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
        }
    );
    

    【讨论】:

    • 感谢@ccordon 的回复,所以这段代码会自动添加外键并与 user_id 匹配?
    • 我试过了,它就像你说的那样工作,但我的问题是这个外键如何与用户 ID 连接并提取与特定用户 ID 相关的数据
    • 您想获取所有具有相同 user_id 的 profile_personals 吗?我就是这么理解你的。
    • 是的,正确,谢谢你的回答,它解决了我的问题。
    猜你喜欢
    • 2019-07-26
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多