Custom joins with Sequelize.literal
See original GitHub issueIssue Description
When you need to add some custom table or a join for a report, there is not always an association defined in the models. For this other ORMs like Rails’ active record allow you to define custom joins without setting up an association.
Example
models.user.findAll({ include: [ {model: models.user_report, as: 'reports', on: Sequelize.literal('user.id = reports.user_id')} ] ...
For this to work I have to have a user to user_report association. This is not always possible and inconvenient to always define.
Describe the solution you’d like
The easiest this would be to allow a completely custom Sequelize.literal() inside the include:
include[ {Sequelize.literal( ' INNER JOIN user_report reports ON user.id = reports.user_id' )} ]
Why should this be in Sequelize
This is how it is done with other ORMs. As more users switch from Rails, Django and Laravel to node, they will be looking for something like this. There are several Stack Overflow questions asking for this. Ex: https://stackoverflow.com/questions/47215961/sequelize-js-join-tables-without-associations
Many issues brought up in the sequelize github could also be easier resolved with this as opposed to looking for all the operators etc within the include clause. Ex: https://github.com/sequelize/sequelize/issues/6718
Describe alternatives/workarounds you’ve considered
The only way I see to not have an association and still joining is a raw query, which erases the convenience of the ORM
Issue Template Checklist
Is this issue dialect-specific?
- No. This issue is relevant to Sequelize as a whole.
- Yes. This issue only applies to the following dialect(s): XXX, YYY, ZZZ
Would you be willing to resolve this issue by submitting a Pull Request?
- Yes, I have the time and I know how to start.
- Yes, I have the time but I don’t know how to start, I would need guidance.
- No, I don’t have the time, although I believe I could do it if I had the time…
- No, I don’t have the time and I wouldn’t even know how to start.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:25
- Comments:27 (11 by maintainers)
Does anyone know a project maintainer? This is a key issue for sequelize popularity
@papb That’s close, but a subquery creates a whole new query inside the original query.
We just need to be able to define the literal
JOIN
to add onto the original query.For example, we just need to be able to add this literal SQL to the query created by sequelize:
INNER JOIN user_report reports ON user.id = reports.user_id