Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left excluding join in sequelize

Tags:

sequelize.js

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: left excluding join

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?

like image 447
mtfurlan Avatar asked Mar 30 '17 15:03

mtfurlan


People also ask

What is a left OUTER JOIN?

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.

What is the difference between left JOIN and left OUTER JOIN?

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.

How do you do joins in Sequelize?

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.


1 Answers

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.

like image 102
piotrbienias Avatar answered Oct 15 '22 13:10

piotrbienias