Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize: relations in both directions needed?

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?

like image 417
Franken Avatar asked Sep 28 '18 04:09

Franken


People also ask

Are there many relations in Sequelize?

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).

Does Sequelize have one relationship?

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.

How do you include two models in Sequelize?

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.


1 Answers

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.

like image 153
Vivek Doshi Avatar answered Oct 20 '22 01:10

Vivek Doshi