I am trying to insert email and generated sessionId into a table in my mysql database (using Sequelize-TypeScript), I first check if the user exists and if the given passwords match. If this is the case, I execute the insert (create) query but it gives me the following error message: Cannot add or update a child row: a foreign key constraint fails (hyteams.sessions, CONSTRAINT sessions_ibfk_1 FOREIGN KEY (email) REFERENCES users (email)).
I tried checking the sequelize models to see if something was wrong with those, but they seem to be fine.
import { Column, DataType, Model, Table } from "sequelize-typescript";
@Table({
tableName: "users",
timestamps: true
})
export default class SequelizeUserModel extends Model {
@Column({
type: DataType.STRING,
allowNull: false,
primaryKey: true
})
declare email: string;
@Column({
type: DataType.STRING,
allowNull: false,
primaryKey: false
})
declare username: string;
}
import { Column, DataType, Model, Table } from "sequelize-typescript";
@Table({
tableName: "sessions",
timestamps: true
})
export default class SequelizeSessionModel extends Model {
@Column({
type: DataType.STRING,
allowNull: false,
primaryKey: true,
references: {
model: "users",
key: "email"
}
})
declare email: string;
@Column({
type: DataType.STRING,
allowNull: false,
primaryKey: true
})
declare sessionid: string;
}
public async findUser(email: string): Promise<User | null> {
const find: SequelizeUserModel | null = await SequelizeUserModel.findOne({ where: { email: email } });
if (find && find.email) {
return this.userMapping.mapUser(find);
} else {
return null;
}
}
public async setSessionId(sessionId: string, email: string): Promise<string> {
const create: SequelizeSessionModel | null = await SequelizeSessionModel.create({ email: email, sessionid: sessionId });
const createdSession: SequelizeSessionModel | null = await SequelizeSessionModel.findOne({ where: { email: email, sessionid: sessionId } });
if (createdSession && createdSession.sessionid) {
return createdSession.sessionid;
} else {
throw new Error("Failed to set session id.");
}
}