Archived
1
0
Fork 0

Add relation between commands and users also claim old commands when a user register with same first & last name

This commit is contained in:
Ethanell 2020-08-17 17:10:21 +02:00
parent 2ca80e5300
commit 3e3765b724
4 changed files with 12 additions and 2 deletions

View file

@ -7,6 +7,7 @@ module.exports = (sequelize, DataTypes) => {
static associate(models) { static associate(models) {
Command.belongsToMany(models.Sandwich, {through: {model: models.SandwichCommand, unique: false}}); Command.belongsToMany(models.Sandwich, {through: {model: models.SandwichCommand, unique: false}});
Command.belongsTo(models.Department); Command.belongsTo(models.Department);
Command.belongsTo(models.User);
} }
} }
Command.init({ Command.init({

View file

@ -6,6 +6,7 @@ module.exports = (sequelize, DataTypes) => {
class User extends Model { class User extends Model {
static associate(models) { static associate(models) {
User.belongsTo(models.Department); User.belongsTo(models.Department);
User.hasMany(models.Command);
} }
checkPassword(password) { checkPassword(password) {

View file

@ -40,11 +40,12 @@ router.post("/", async (req, res) => {
lastName: req.body.lastName, lastName: req.body.lastName,
price: price price: price
}); });
let user = await models.User.findOne({where: {firstName: req.body.firstName, lastName: req.body.lastName}});
if (user)
await command.setUser(user);
await command.setDepartment(department); await command.setDepartment(department);
for (let data of sandwiches) for (let data of sandwiches)
try { try {
console.log(command.id);
console.log(data);
await models.SandwichCommand.create({CommandId: command.id, SandwichName: data[0], date: data[1]}); await models.SandwichCommand.create({CommandId: command.id, SandwichName: data[0], date: data[1]});
} catch (e) { } catch (e) {
await command.destroy(); await command.destroy();

View file

@ -36,9 +36,16 @@ router.get("/", async (req, res) => {
lastName: req.body.lastName, lastName: req.body.lastName,
passwordHash: req.body.password passwordHash: req.body.password
}); });
await user.setDepartment(department); await user.setDepartment(department);
req.session.user = user; req.session.user = user;
res.redirect("/"); res.redirect("/");
for (let c of await models.Command.findAll({where: {
firstName: user.firstName,
lastName: user.lastName,
UserUsername: null
}}))
await c.setUser(user);
} catch (e) { } catch (e) {
res.render("error", {message: "Registration fail !", error: {}}); res.render("error", {message: "Registration fail !", error: {}});
throw e; throw e;