Skip to content
Advertisement

Set an alias for the junction table in a many to many relationship in sequelize

Apologizes if the title is confusing, I’m unsure what terminology to use here.

Basically, I have three (Four, technically, but the fourth is nearly identical to user.model.js) models:

user.model.js

JavaScript

item.model.js

JavaScript

useritems.model.js

JavaScript

In my controller, I have

JavaScript

Now this works perfectly fine, except for the fact that the ‘seen’ and ‘owned’ columns are added to an additional object called UserItems.

Example of the returned item:

JavaScript

This is less than ideal for what I’m using the data for – basically, there’s also a Guest table with the equivalent many-to-many relation with the Item table, and the join table for it is called GuestItems. So when I search for a guest – the above result spits out the same data, but with GuestItems instead of UserItems.

What I want to happen, is have UserItems/GuestItems be renamed to Items. Or ideally, just have the ‘seen’ and ‘owned’ columns from the UserItems/GuestItems table be added to the rest of the results, without being its own ‘UserItems/GuestItems’ attribute.

Is this possible to accomplish with Sequelize? I’d really rather not have to add another step of renaming the object in the return.

Advertisement

Answer

To just rename the UserItems table you can use the “as” option in the “through” option:

JavaScript

This should return Item as:

JavaScript

As for saving them directly in ‘Item’ not sure if that can be done with sequelize finders, you probably need to write your own raw SQL query to join the ‘seen’ and ‘owned’ columns on ‘UserItems’ with ‘Item’.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement