Node.js 如何使用Sequelize创建特定密钥的关联?
我已经设置好了所有的模型,并且我有一个使用表ID从一个表到另一个表的外键。我还想将url属性作为外键,但是每当我包含“type:DataTypes.STRING”时,我就会得到以下错误Node.js 如何使用Sequelize创建特定密钥的关联?,node.js,sequelize.js,Node.js,Sequelize.js,我已经设置好了所有的模型,并且我有一个使用表ID从一个表到另一个表的外键。我还想将url属性作为外键,但是每当我包含“type:DataTypes.STRING”时,我就会得到以下错误 Unhandled rejection SequelizeDatabaseError: (conn=195, no: 1215, SQLState: HY000) Cannot add foreign key constraint 当我不包含数据类型时,它会添加FK,但作为一个整数。如何创建专门引用URL属性的
Unhandled rejection SequelizeDatabaseError: (conn=195, no: 1215, SQLState: HY000) Cannot add foreign key constraint
当我不包含数据类型时,它会添加FK,但作为一个整数。如何创建专门引用URL属性的FK
谢谢
categories.belongsTo(categoriesTop, {
foreignKey: {
name: 'topCategoriesUrl',
allowNull: false,
type: DataTypes.STRING,
referencesKey: "url"
}
});
类别与顶层模式
const { Sequelize, DataTypes } = require('sequelize');
const db = require('../dbconfig');
const categories_top = db.define('categories_top', {
url: {
type: DataTypes.STRING,
allowNull: false
},
title: {
type: DataTypes.STRING,
allowNull: false
},
subtitle: {
type: DataTypes.STRING,
allowNull: false
},
image: {
type: DataTypes.STRING
}
}, {
freezeTableName: true,
timestamps: false
});
module.exports = categories_top;
类别模式
const { Sequelize, DataTypes } = require('sequelize');
const db = require('../dbconfig');
const topCategories = require('./category_top');
const categories = db.define('categories', {
title: {
type: DataTypes.STRING,
allowNull: false
},
subtitle: {
type: DataTypes.STRING,
allowNull: true
},
url: {
type: DataTypes.STRING,
allowNull: false
},
image: {
type: DataTypes.STRING
}
}, {
freezeTableName: true,
timestamps: false
});
module.exports = categories;
您必须在
category\u top
中将url
定义为主键或唯一约束,如下所示:
const categories_top = db.define('categories_top', {
url: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true, // Either define it as a primary key
unique: true // OR as a unique constraint
},
title: {
type: DataTypes.STRING,
allowNull: false
},
subtitle: {
type: DataTypes.STRING,
allowNull: false
},
image: {
type: DataTypes.STRING
}
}, {
freezeTableName: true,
timestamps: false
});
阅读有关外键的更多信息。您是否应该将
topCategoriesUrl
列定义为categoriesTop
模型中的字符串,而不是外键定义中的字符串?我也这样做了。categoriesTop中的URL设置为字符串,这就是为什么我认为我的错误是由于尝试引用ce url列。我认为它只是引用ID列,而不是url列。你能发布两个表的模型吗?我将它们添加到问题中,但不起作用。我尝试将PK和UK添加到url中,但有相同的问题。我理解FKs是什么,但当你使用ORM时,一些规则会改变。。。