From fe336be25815fb31b19235ff48a6f3e150df609f Mon Sep 17 00:00:00 2001 From: Fabio Manganiello <fabio@manganiello.tech> Date: Mon, 24 Mar 2025 01:57:55 +0100 Subject: [PATCH] =?UTF-8?q?=EF=87=80=20=20Added=20foreign=20key=20definiti?= =?UTF-8?q?ons=20to=20Sequelize=20models.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We need the constraints to be explicitly defined on the table definitions too, otherwise JOINs won't work. --- src/db/Db.ts | 50 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/src/db/Db.ts b/src/db/Db.ts index 4e0f9ad..326ea9a 100644 --- a/src/db/Db.ts +++ b/src/db/Db.ts @@ -127,47 +127,83 @@ class Db { */ public GPSData() { - return this.locationDb.define('GPSData', GPSData(this.locationTableColumns), { + const tableDef = this.locationDb.define('GPSData', GPSData(this.locationTableColumns), { tableName: this.locationTable, timestamps: false, }); + + tableDef.hasOne(this.UserDevice(), { + sourceKey: this.locationTableColumns.deviceId, + foreignKey: 'id', + as: 'device', + }); + + return tableDef; } public Role() { - return this.appDb.define('Role', Role(), { + const tableDef = this.appDb.define('Role', Role(), { tableName: this.tableName('roles'), timestamps: false, }); + + return tableDef; } public User() { - return this.appDb.define('User', User(), { + const tableDef = this.appDb.define('User', User(), { tableName: this.tableName('users'), timestamps: false, }); + + return tableDef; } public UserDevice() { - return this.appDb.define('UserDevice', UserDevice(), { + const tableDef = this.appDb.define('UserDevice', UserDevice(), { tableName: this.tableName('user_devices'), timestamps: false, }); + + tableDef.belongsTo(this.User(), { + foreignKey: 'userId', + as: 'user', + }); + + return tableDef; } public UserRole() { - return this.appDb.define('UserRole', UserRole(), { + const tableDef = this.appDb.define('UserRole', UserRole(), { tableName: this.tableName('users_roles'), timestamps: false, }); + + tableDef.belongsTo(this.User(), { + foreignKey: 'userId', + as: 'user', + }); + + tableDef.belongsTo(this.Role(), { + foreignKey: 'roleId', + as: 'role', + }); + + return tableDef; } public UserSession() { - const ret = this.appDb.define('UserSession', UserSession(), { + const tableDef = this.appDb.define('UserSession', UserSession(), { tableName: this.tableName('user_sessions'), timestamps: false, }); - return ret; + tableDef.belongsTo(this.User(), { + foreignKey: 'userId', + as: 'user', + }); + + return tableDef; } }