gpt4 book ai didi

node.js - Sequelize Postgresql 没有强制外部约束

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

我有这些模型。 (门票和事件)。事件有很多票,一张票属于一个事件。
模型/ticket.js

'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Ticket extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
Ticket.belongsTo(models.Event, {
foreignKey: "event_id",
as: "event"
})

Ticket.hasMany(models.Order, {
foreignKey: "ticket_id",
as: "orders"
})
}
};
Ticket.init({
ticket_type: {
type: DataTypes.STRING, allowNull: false, validate: { notNull: { args: true, msg: "Ticket type is required" } }
},
event_id: {
type: DataTypes.INTEGER, allowNull: false, validate: { notNull: { args: true, msg: "event_id is required" } }
},
ticket_quota: {
type: DataTypes.INTEGER, default: 0
},
ticket_price: {
type: DataTypes.FLOAT, default: 1
}
}, {
sequelize,
modelName: 'Ticket',
});
return Ticket;
};
模型/事件.js
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Event extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
Event.hasMany(models.Ticket, {
foreignKey: "event_id",
as: "tickets"
})
}
};
Event.init({
event_name: {
type: DataTypes.STRING, allowNull: false, validate: { notNull: { args: true, msg: "Event name is required" } }
},
event_date: {
type: DataTypes.DATE, allowNull: false, validate: { notNull: { args: true, msg: "Event Date is required" } }
},
event_location: {
type: DataTypes.STRING, allowNull: false, validate: { notNull: { args: true, msg: "Event location is required" } }
},
event_description: DataTypes.STRING
}, {
sequelize,
modelName: 'Event',
});
return Event;
};
从这里可以看出,票证与事件相关联。问题是当我尝试插入事件表中不存在的具有 event_id 的票证时。尽管有限制,它仍然插入。
任何人都知道出了什么问题以及如何解决?
先感谢您。

最佳答案

您需要在关联中使用 allowNull: false

  // define association here
Event.hasMany(models.Ticket, {
foreignKey: "event_id",
as: "tickets",
allowNull: false,
})

关于node.js - Sequelize Postgresql 没有强制外部约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64615200/

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