 Added foreign key definitions to Sequelize models.

We need the constraints to be explicitly defined on the table
definitions too, otherwise JOINs won't work.
This commit is contained in:
Fabio Manganiello 2025-03-24 01:57:55 +01:00
parent 3e88272277
commit fe336be258
Signed by: blacklight
GPG key ID: D90FBA7F76362774

View file

@ -127,47 +127,83 @@ class Db {
*/ */
public GPSData() { public GPSData() {
return this.locationDb.define('GPSData', GPSData(this.locationTableColumns), { const tableDef = this.locationDb.define('GPSData', GPSData(this.locationTableColumns), {
tableName: this.locationTable, tableName: this.locationTable,
timestamps: false, timestamps: false,
}); });
tableDef.hasOne(this.UserDevice(), {
sourceKey: this.locationTableColumns.deviceId,
foreignKey: 'id',
as: 'device',
});
return tableDef;
} }
public Role() { public Role() {
return this.appDb.define('Role', Role(), { const tableDef = this.appDb.define('Role', Role(), {
tableName: this.tableName('roles'), tableName: this.tableName('roles'),
timestamps: false, timestamps: false,
}); });
return tableDef;
} }
public User() { public User() {
return this.appDb.define('User', User(), { const tableDef = this.appDb.define('User', User(), {
tableName: this.tableName('users'), tableName: this.tableName('users'),
timestamps: false, timestamps: false,
}); });
return tableDef;
} }
public UserDevice() { public UserDevice() {
return this.appDb.define('UserDevice', UserDevice(), { const tableDef = this.appDb.define('UserDevice', UserDevice(), {
tableName: this.tableName('user_devices'), tableName: this.tableName('user_devices'),
timestamps: false, timestamps: false,
}); });
tableDef.belongsTo(this.User(), {
foreignKey: 'userId',
as: 'user',
});
return tableDef;
} }
public UserRole() { public UserRole() {
return this.appDb.define('UserRole', UserRole(), { const tableDef = this.appDb.define('UserRole', UserRole(), {
tableName: this.tableName('users_roles'), tableName: this.tableName('users_roles'),
timestamps: false, timestamps: false,
}); });
tableDef.belongsTo(this.User(), {
foreignKey: 'userId',
as: 'user',
});
tableDef.belongsTo(this.Role(), {
foreignKey: 'roleId',
as: 'role',
});
return tableDef;
} }
public UserSession() { public UserSession() {
const ret = this.appDb.define('UserSession', UserSession(), { const tableDef = this.appDb.define('UserSession', UserSession(), {
tableName: this.tableName('user_sessions'), tableName: this.tableName('user_sessions'),
timestamps: false, timestamps: false,
}); });
return ret; tableDef.belongsTo(this.User(), {
foreignKey: 'userId',
as: 'user',
});
return tableDef;
} }
} }