首页 > 解决方案 > Sequelize 外键未创建

问题描述

我尝试在 NodeJS for MariaDB 中使用 Sequelize 在 2 个表之间创建关系。

我有 2 个表orderlocal,表 order 需要表 local 的信息之一

订单表包含有关订单的信息(id:1,类型:夹克,颜色:蓝色,tracking_number:TR123 )

local表包含有关订单存储地点的信息(地址:20 rue madeline,城市:巴黎

我试图链接这两个表,但它不起作用,没有创建外键

模型/order.js

module.exports = (sequelize, DataTypes) => {
    const Order = sequelize.define('order', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        trackingNumber: {
            type: DataTypes.STRING,
            allowNull: false
        },
        type: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        color: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        email: {
            type: DataTypes.STRING,
            allowNull: false
        },
        tel: {
            type: DataTypes.STRING(10),
            allowNull: false
        }
    }, {
        timestamps: true,
        createdAt: true,
        updatedAt: 'updateTimestamp'
    })

    Order.associate = function (models) {
        Order.hasOne(models.local);
    }

    return Order;
}

模型/local.js


module.exports = (sequelize, DataTypes) => {
    const Local = sequelize.define('local', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        adress: {
            type: DataTypes.STRING,
            allowNull: false
        },
        informations_about: {
            type: DataTypes.STRING,
            allowNull: false
        },
        contact: {
            type: DataTypes.STRING,
            allowNull: false
        },
        city: {
            type: DataTypes.STRING,
            allowNull: false
        },
        zip: {
            type: DataTypes.STRING(5),
            allowNull: false
        },

    }, {
        timestamps: true,
        createdAt: true,
        updatedAt: 'updateTimestamp'
    })
    return Local;
}

应用程序.js

// Imports
const express = require('express')
const morgan = require('morgan')
const db = require('./database')
const sequelize = require('./database').sequelize;

var apiRouter = require('./apiRouter.js').router;
var helmet = require('helmet');

const app = express()
const port = process.env.PORT || 3000;

// Init server
app.use(morgan('combined'))

// Parser config
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// Security API
app.use(helmet());
app.disable('x-powered-by');


app.use(({ res }) => {
    res.status(404).json({ message: "404 Not Found" })
})

db.sequelize.authenticate()
    .then(_ => console.log("La connexion à bien été établie."))
    .catch(error => console.log(`error ${error}`))

db.sequelize.sync({ force: true })
    .then(_ => {
        console.log("Base de donnée synchronisée.")
        app.use('/api/', apiRouter);
    })


app.listen(port, () => {
    console.log("Server is up and listening in " + port)
})


数据库.js

const fs = require('fs')
const path = require('path')
const { Sequelize } = require('sequelize')
const db = {}
const models = path.join(__dirname, 'models') // correct it to path where your model files are

const sequelize = new Sequelize(
    '',
    '',
    '',
    {
        host: 'localhost',
        dialect: 'mariadb',
        dialectOptions: {
            useUTC: false, // for reading from database
        },
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        },
        logging: false
    }
)

var basename = path.basename(module.filename)

fs
    .readdirSync(models)
    .filter(function (file) {
        return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
    })
    .forEach(function (file) {
        const model = require(path.join(__dirname + '/models', file))(sequelize, Sequelize.DataTypes)
        db[model.name] = model
    })

Object.keys(db).forEach(function (modelName) {
    if (db[modelName].associate) {
        db[modelName].associate(db)
    }
})

db.Sequelize = Sequelize // for accessing static props and functions like Op.or
db.sequelize = sequelize // for accessing connection props and functions like 'query' or 'transaction'

module.exports = db

尽管model/order.js中的关联函数不起作用,但我的订单表中没有键

标签: javascriptnode.jssequelize.js

解决方案


您必须手动调用所有associate函数才能注册模型之间的关联,并且只有在所有模型都已在 Sequelize 实例中注册之后。你可以看看我的另一个答案,看看你是怎么做到的。
请显示database模块的内容,然后我可能会更正我的答案或附加更多有用的提示。


推荐阅读