I was wandering if there is a way to access the models from sequelize.models.
I found this project, but the function "getModel" it will just return an any type:
https://github.com/alexjoverm/unnamed-server/blob/master/src/modules/db/db.service.ts
Do you have any suggestion how to make it work?
Hey @JustGreg, you can access models by key like this:
import {Sequelize} from 'sequelize-typescript';
const sequelize = new Sequelize(...);
sequelize._['User'].findAll(...)
or
import {Sequelize} from 'sequelize-typescript';
const sequelize = new Sequelize(...);
sequelize._.User.findAll(...)
I will add a more reasonable way in the future. I admit, sequelize._['User'] is ugly somehow.
Thank you @RobinBuschmann ,
I just tried to add this to the function getModel but I can't get the types of the selected model.
public getModel<T>(modelName: string): Model<T> {
return this.db._[modelName];
}
so i can use:
this.db.getModel<User>('User');
Typescript error: Type 'typeof Model' is not assignable to type 'Model<T>'.
Property '$add' is missing in type 'typeof Model'.'
@JustGreg Try this one:
interface ModelClass<T> {
new(values?: any, options?: IBuildOptions): T;
}
function getModel<T>(modelName: string): ModelClass<T> & typeof Model {
return sequelize._[modelName] as any;
}
You want typeof Model, not an instance of Model :)
That works great. Thank you!
Most helpful comment
@JustGreg Try this one:
You want
typeof Model, not an instance of Model :)