gpt4 book ai didi

mysql - Sequelize 关联不生成外键

转载 作者:行者123 更新时间:2023-12-03 22:24:46 26 4
gpt4 key购买 nike

Sequelize 不会自动创建外键,并且会在“fieldset”中抛出“no column”userId”错误。我尝试在下面提供所有信息。由于我的代码是 100% 正确的,因此我完全不知道该从哪里开始。 (参见下文)
所以我有一个产品和用户模型。之前两者都工作正常。我添加了一些代码来建立关系:

Product.belongsTo(User, { constraints: true, onUpdate: "CASCADE" });
User.hasMany(Product);
我也在同步数据库时使用了 {force: true} 并在表刷新后将其删除。我试过在这些步骤之后重新启动电脑,重新启动工作台,创建一个新数据库并更改连接以连接到新数据库,但它仍然没有在我的产品架构中放置“userId”列。
到目前为止,我已经让两个人检查了这段代码,他们确认我的语法很好,并且同样感到困惑。我也相信自己这不是不正确的,因为我遵循的是信誉良好的类(class),现在我不得不复制并粘贴他的代码来代替我的代码,以防万一,这没有用。
产品型号:
const Sequelize = require("sequelize");

const sequelize = require("../util/database");

const Product = sequelize.define("product", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
title: Sequelize.STRING,
price: {
type: Sequelize.DOUBLE,
allowNull: false,
},
image_url: {
type: Sequelize.STRING,
allowNull: false,
},
description: {
type: Sequelize.STRING,
allowNull: false,
},
});

module.exports = Product;
用户模型:
const Sequelize = require("sequelize");

const sequelize = require("../util/database");

const User = sequelize.define("user", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: Sequelize.STRING,
email: Sequelize.STRING,
});

module.exports = User;
同步代码(我创建了一个测试用户,因为类(class)处于我们测试的阶段,我们可以制作一个):
// db.sync({ force: true })
db.sync()
.then((result) => {
return User.findByPk(1);
// console.log(result);
})
.then((user) => {
if (!user) {
return User.create({ name: "Max", email: "test@test.com" });
}
return user;
})
.then((user) => {
app.listen(5000);
})
.catch((err) => {
console.log(err);
});
连接是 100% 连接的,因为我的数据库中的表发生了事情,只是 Sequelize 应该从我的关联自动生成的“userId”列不会出现。
还尝试在我的 Product.belongsTo() 代码行中放入一个外键:“userId”以尝试隐式设置它。那甚至没有用。
因此我卡住了,无法继续使用我的 sql 代码。
Github repo 如果需要进一步的代码:
https://github.com/NinjaInShade/online-shop

最佳答案

我对你的代码进行了一些关于关联和外键的修改,你有两种方法来创建列 userId 和外键:

  • 使用 userId 选项向 Product 模型添加 references 字段定义,如下所示:
  •   userId: {
    allowNull: true,
    type: Sequelize.INTEGER,
    references: {
    model: 'users',
    key: 'id'
    }
    }
  • 使用 sync 方法单独同步模型:
  • User.sync({ force: true })
    .then(() => {
    Product.sync({ force: true }).then(() => {
    app.listen(5000);
    })
    })
    不幸的是,官方文档没有说明为什么 sync 中的 Sequelize 方法与单独模型的 sync 相比表现不同。
    通常我使用迁移,这就是为什么我没有这个问题。

    关于mysql - Sequelize 关联不生成外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65748750/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com