I have two tables, where one table has the ID of the other. 1:1 relation. So something like
EventFeedback
somePrimaryKey
userEventID
UserEvent
userEventID
Sequalize has the relation defined with
models.UserEvent.hasOne(models.EventFeedback, { foreignKey: 'userEventID' });
I need all entries in UserEvent
that do not have an entry in EventFeedback
, which is an exclusionary join.
Stealing images from this article because they have nice individual images:
They even give example code!
SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL
How do I do this in sequelize? Do I just need to do a left join and process it manually?
A left outer join is a method of combining tables. The result includes unmatched rows from only the table that is specified before the LEFT OUTER JOIN clause. If you are joining two tables and want the result set to include unmatched rows from only one table, use a LEFT OUTER JOIN clause or a RIGHT OUTER JOIN clause.
There really is no difference between a LEFT JOIN and a LEFT OUTER JOIN. Both versions of the syntax will produce the exact same result in PL/SQL. Some people do recommend including outer in a LEFT JOIN clause so it's clear that you're creating an outer join, but that's entirely optional.
There are two ways you can create JOIN queries and fetch data from multiple tables with Sequelize: Create raw SQL query using sequelize. query() method. Associate related Sequelize models and add the include option in your Sequelize query method.
You need to eager load EventFeedback
when querying UserEvent
and add proper where
clause. You also need to define that EventFeedback
is not required in the result so the query will generate LEFT JOIN
instead INNER JOIN
UserEvent.all({
include: [
model: EventFeedback,
required: false, // do not generate INNER JOIN
attributes: [] // do not return any columns of the EventFeedback table
],
where: sequelize.where(
sequelize.col('EventFeedback.userEventID'),
'IS',
null
)
}).then(userEvents => {
// user events...
});
In the code above the sequelize
is an instance of Sequelize with model defined in it. You can also refer to the documentation of sequelize.where()
and sequelize.col()
methods.
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