I have two existing tables in my database: "user" with the columns "id" and "depId" and "department" with "id" and "name". (user.depId ist the foreign key for department.id)
Now I'd like to create a sequelize model for this.
I already added this
User.belongsTo (Department, { foreignKey: 'depId', targetKey: 'id'});
Do I have to add this also:
Department.HasMany(User)
or is one direction enough to work properly?
The A.hasMany(B) association means that a One-To-Many relationship exists between A and B , with the foreign key being defined in the target model ( B ). These three calls will cause Sequelize to automatically add foreign keys to the appropriate models (unless they are already present).
Using the Sequelize hasOne() association method. The Sequelize hasOne() association method is used to establish an association between two defined Sequelize models. The association method allows you to link two models so that you can retrieve data from both tables with one query execution.
Your solution, along with using include: {all:true} in my findAll query, did the trick. instead of using include: {all:true} in findAll you can use include: {model: models. User, as: 'createdByUser'} , etc. Be sure to use as: in all associations to the same model in your Sequelize model declaration.
sequelize: relations in both directions needed?
Depends
So here we go :
User.belongsTo (Department, { foreignKey: 'depId', targetKey: 'id'});
This will help you to get Department via User via sequelize association ,
Department.HasMany(User)
But this what you need if you want to get User via Department via sequelize association
So define any one of it if you just gonna needed one , but best practice is to define both way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With