错误:Sequelize 模型外键定义不正确

问题描述 投票:0回答:1

我有 2 个表模式 Customer 和 Cart

客户.js

module.exports = (sequelize, DataTypes) => {
    const Customer = sequelize.define("custom", {
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        title: {
            type: DataTypes.STRING,
            allowNull: false
        },
        username: {
            type: DataTypes.STRING,
            allowNull: false
        },
        email: {
            type: DataTypes.STRING,
            allowNull: false
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false
        },
        address: {
            type: DataTypes.STRING,
            allowNull: true
        },
        date: {
            type: DataTypes.STRING,
            allowNull: false,
        }
    }, {
        timestamps: false
    });

    Customer.associate = (models) => {
        Customer.hasOne(models.cart, { foreignKey: 'customerId' });
    };

    return Customer;
};

Cart.js

module.exports = (sequelize, DataTypes) => {
    const Cart = sequelize.define("cart", {
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        customerId: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'custom',
                key: 'id'
            }
        }

    }, {
        timestamps: false
    });

    Cart.associate = (models) => {
        // Define associations here
        Cart.belongsTo(models.customer, { foreignKey: 'customerId' });
    };

    return Cart;
};

我有每个模型的index.js文件

客户/index.js

const dbConfig = require("../../config/db.config.js");

const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
    host: dbConfig.HOST,
    dialect: dbConfig.dialect,
    operatorsAliases: false,

    pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
    }
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.customer = require("./customer.js")(sequelize, Sequelize);
db.cart = require("../cart/cart.js")(sequelize, Sequelize);
db.customer.associate(db);
module.exports = db;

购物车/index.js

const dbConfig = require("../../config/db.config.js");

const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
    host: dbConfig.HOST,
    dialect: dbConfig.dialect,
    operatorsAliases: false,

    pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
    }
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.cart = require('./cart.js')(sequelize, Sequelize);
db.customer = require('../customer/customer.js')(sequelize, Sequelize);
db.customer.associate(db);
module.exports = db;

以及我的 server.js 或我正在运行的主文件

const express = require('express');
const cors = require("cors");
const session = require('express-session');
const crypto = require('crypto');
const app = express();

var corsOptions = {
    origin: "http://localhost:3000"
};

app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Generate a random secret key
const secretKey = crypto.randomBytes(32).toString('hex');

app.use(session({
    secret: secretKey,
    resave: false,
    saveUninitialized: false
}));

const db_customer = require("./app/database/models/customer/index.js");
// const db_product = require("./app/database/models/product/index.js");

// db.sequelize.sync();
db_customer.sync();
const PORT = 4000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}.`);
});

运行 Node server.js 后

我收到此错误 在 Socket.emit (节点:事件:518:28) 在 addChunk (节点:内部/流/可读:559:12) 在 ReadAddChunkPushByteMode (节点:内部/流/可读:510:3) 在 Readable.push (节点:内部/流/可读:390:5) { 代码:'ER_CANT_CREATE_TABLE', 错误号:1005, sqlState: 'HY000', sqlMessage: '无法创建表

s3941488_fsd_a2
carts
(errno: 150 "外键约束格式不正确")', sql: '如果不存在则创建表
carts
id
整数自动增量,
customerId
整数不为空,主键(
id
),外键(
customerId
)参考
custom
id
)开在更新级联时删除级联) ENGINE=InnoDB;', 参数:未定义 }, sql: '如果不存在则创建表
carts
id
整数自动增量,
customerId
整数不为空,主键(
id
),外键(
customerId
)参考
custom
id
)开在更新级联时删除级联) ENGINE=InnoDB;', 参数: {} }

当我从购物车模型架构中的 customerId 属性中删除引用属性时,它解决了问题,但我需要数据完整性。我不确定是什么原因导致问题

node.js express sequelize.js
1个回答
0
投票

这是因为您以错误的顺序导入模型。

cart
customer
之前被定义,所以显然它不知道
custom.id

db.cart = require('./cart.js')(sequelize, Sequelize);
db.customer = require('../customer/customer.js')(sequelize, Sequelize);

应该首先加载

customer

db.customer = require('../customer/customer.js')(sequelize, Sequelize);
db.cart = require('./cart.js')(sequelize, Sequelize);
© www.soinside.com 2019 - 2024. All rights reserved.