mysql - 使用 Sequelize 添加外键约束

标签 mysql foreign-keys sequelize.js

我正在与 Sequelize 协会合作。我见过很多添加外键的方法,我的做法正确吗?

我想做的是从我的父表(users,“user_id”)向我的 profile_personals 表添加外键约束

const Sequelize = require('sequelize')
const db = require('../database/db.js')
const Users = require('../model/User.js')

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

        biography: {
            type: Sequelize.STRING
        },
        fk_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
    }
)

最佳答案

你尝试过关联方法吗? 我认为 HasManyHasOne 方法会起作用。

http://docs.sequelizejs.com/class/lib/associations/has-many.js~HasMany.html

user.hasMany(db.profile_personals, {foreignKey: 'user_id'})

关于mysql - 使用 Sequelize 添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54990205/

相关文章:

php - 比较 2 个表中的每一行

php - php 中的多个 mysql 查询

mysql - 将几何图形插入带有变量的 mySQL 数据库

javascript - 不更新,但 promise 返回成功

php - 拉拉维尔 : How do I get records from pivot table whereby its foreign key does not reference a primary key?

java - PostgreSQL JDBC - 可以删除但不能重新创建索引

c# - Web API 核心 : "FOREIGN KEY constraint failed" error during POST request SQLite

mysql - 为什么要为外键烦恼?

node.js - SEQUELIZE : belongsTo called with something that's not a subclass of Sequelize. 模型

mysql - 如何在 sequelize 中更新 through-NM-attribute?