Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize eager load nested associations

I'm fairly new to Sequelize, and I can't seem to find an answer to my question.

I have a model 'team' which has associations defined as:

    team.hasMany(members, {foreignKey: 'memberId', onDelete: 'cascade'});
    team.belongsTo(memberDetails, {as: 'type1', foreignKey: 'type1Id'});
    team.belongsTo(memberDetails, {as: 'type2', foreignKey: 'type2Id'});

I want to load team rows from the database, and as I load each row I want the (some of) the associations to be included as well. I use the following code:

team.findAll({
   include: [
               {
                   model: memberDetails,
                   as: 'type1'
               }
            ]
})

This loads the teams as expected, and loads associated members, and also loads and attaches details for 'type1' members per the include.

However, the memberDetail model also has associations:

    memberDetails.belongsTo(memberInfo, {as: 'type1', foreignKey: 'type1Id'});
    memberDetails.belongsTo(memberInfo, {as: 'type2', foreignKey: 'type2Id'});

What I want is the memberInfo associations to be loaded for each member loaded - similar to the INCLUDEd memberDetails, but I don't know how to specify the INCLUDE for the eagerly loaded associations.

Can anyone help?

like image 951
JeffR Avatar asked Feb 17 '18 22:02

JeffR


People also ask

What is eager loading Sequelize?

Sequelize eager loading is a way to fetch data from multiple tables that have relations between each other. When you use the eager loading technique, the generated SQL query will have one or more JOIN clauses.

How do I add an association in model Sequelize?

Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.

What is findByPk?

findByPk ​ The findByPk method obtains only a single entry from the table, using the provided primary key. const project = await Project. findByPk(123); if (project === null) {

What is eager load?

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by the use of the Include method. It means that requesting related data be returned along with query results from the database.


1 Answers

You could do something like this, as explained in the Sequelize Doc about nested eager loading.

team.findAll({
  include: [{
    model: memberDetails,
    as: 'type1Details',
    include: [{
      model: memberInfo,
      as: 'type1Info'
    }]
  }]
});
like image 181
oniramarf Avatar answered Oct 14 '22 00:10

oniramarf