From 3e3765b72489384dd1012cb0d29906152b463bd5 Mon Sep 17 00:00:00 2001 From: flifloo Date: Mon, 17 Aug 2020 17:10:21 +0200 Subject: [PATCH] Add relation between commands and users also claim old commands when a user register with same first & last name --- models/command.js | 1 + models/user.js | 1 + routes/command.js | 5 +++-- routes/register.js | 7 +++++++ 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/models/command.js b/models/command.js index 924a5fa..817d86a 100644 --- a/models/command.js +++ b/models/command.js @@ -7,6 +7,7 @@ module.exports = (sequelize, DataTypes) => { static associate(models) { Command.belongsToMany(models.Sandwich, {through: {model: models.SandwichCommand, unique: false}}); Command.belongsTo(models.Department); + Command.belongsTo(models.User); } } Command.init({ diff --git a/models/user.js b/models/user.js index 9236d7c..ffeee53 100644 --- a/models/user.js +++ b/models/user.js @@ -6,6 +6,7 @@ module.exports = (sequelize, DataTypes) => { class User extends Model { static associate(models) { User.belongsTo(models.Department); + User.hasMany(models.Command); } checkPassword(password) { diff --git a/routes/command.js b/routes/command.js index f62df3e..6e60571 100644 --- a/routes/command.js +++ b/routes/command.js @@ -40,11 +40,12 @@ router.post("/", async (req, res) => { lastName: req.body.lastName, 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); for (let data of sandwiches) try { - console.log(command.id); - console.log(data); await models.SandwichCommand.create({CommandId: command.id, SandwichName: data[0], date: data[1]}); } catch (e) { await command.destroy(); diff --git a/routes/register.js b/routes/register.js index 2ca5969..ea41908 100644 --- a/routes/register.js +++ b/routes/register.js @@ -36,9 +36,16 @@ router.get("/", async (req, res) => { lastName: req.body.lastName, passwordHash: req.body.password }); + await user.setDepartment(department); req.session.user = user; 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) { res.render("error", {message: "Registration fail !", error: {}}); throw e;