gpt4 book ai didi

javascript - 无法添加外键约束

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

我已经检查了 this answer 并确保两种情况都是正确的。但仍然存在创建约束的问题:

模型:

user.js

'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}, {});
User.associate = function(models) {
models.User.hasMany(models.Answer);
};
return User;
};

answer.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Answer = sequelize.define('Answer', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
userId: {
type: DataTypes.INTEGER,
references: {
model: 'Users',
key: 'id'
},
allowNull: true
},
content: DataTypes.TEXT
}, {});
Answer.associate = function(models) {
models.belongsTo(models.User)
};
return Answer;
};

移民

...-create-user.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
username: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Users');
}
};

...create-answer.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Answers', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
allowNull: true,
type: Sequelize.INTEGER
},
content: {
allowNull: false,
type: Sequelize.TEXT
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Answers');
}
};

还有什么问题?是因为 allowNull: true 吗?但我确信这不应该是这种情况,因为我还使用 allowNull: false 测试了它是否有效,但它没有。

我也完全尝试过 model: User.INTEGER(11) 但没有任何效果。我看不到 PHPMyAdmin 上的外键约束。

最佳答案

你应该添加

userId: {
type: Sequelize.INTEGER,
references: {
model: 'Users',
key: 'id'
},
allowNull: true
}

在 create-answer.js 中

代替
userId: {
allowNull: true,
type: Sequelize.INTEGER
},

关于javascript - 无法添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61753766/

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