Lazarus Rising
Lazarus Rising

Reputation: 2675

Sequelize two associate tables by an intermediate third table

So, I finally made associations work in my sequelize code. Or so I thought.

I have table A associated to table B and table B associated to table C via foreign keys. I want to get rows from A using filters from A, B and C. If C where out of the picture I would do something like this:

 models.A.findOne({
            attributes: ['id', 'col1', 'col2'],
            where: {
                  col1: value1, 
                  col3: value3
            }, 
            include: [{model: models.B, required: true}]
        }).then(function (result) {
            res.send(result);
        }).catch(function(error){
            console.log(error);
            res.send(error);
        });    

Note that col3 is a field in table B.

Now what I want to do would ideally be written as:

 models.A.findOne({
            attributes: ['id', 'col1', 'col2'],
            where: {
                  col1: value1, 
                  col3: value3,
                  col5: value5
            }, 
            include: [{model: models.B, required: true}, {model: models.C, required: true}]
        }).then(function (result) {
            res.send(result);
        }).catch(function(error){
            console.log(error);
            res.send(error);
        });   

Col5 is a field of table C.

Doing so (rightfully) gives me an error: C is not connected to A. I know that A is connected to B and B to C because I define these connections in the models. But I can't define even cross - table associations - like that of A and C.

Firstly I would not know how to do that, and secondly, associations may include chains of up to 5 tables. When I say chains, I mean series of associations, not parallel associations to the same table.

How does sequelize handle this scenario?

Upvotes: 0

Views: 1120

Answers (1)

Lazarus Rising
Lazarus Rising

Reputation: 2675

Ok, that was shameful.

I figured it out. The notation would be as follows:

 models.A.findOne({
            attributes: ['id', 'col1', 'col2'],
            where: {
                  col1: value1, 
                  col3: value3,
                  col5: value5
            }, 
            include: [{model: models.B, required: true}, include:[{model: models.C, required: true}]]
        }).then(function (result) {
            res.send(result);
        }).catch(function(error){
            console.log(error);
            res.send(error);
        });  

Basically, nested associations are written just like that in sequelize - nested.

Thanks to this source http://lorenstewart.me/2016/09/12/sequelize-table-associations-joins/ for the thorough and simple explanation.

Upvotes: 1

Related Questions