Nested relations with Sequelize

前端 未结 2 1786
余生分开走
余生分开走 2020-12-29 20:03

I am using Sequelize with Node + MySQL.

I have a model structure similar to this:

// models:
var Group, Issue,         


        
相关标签:
2条回答
  • 2020-12-29 20:29

    If you want to eager load all nested associations use this function.

    Issue.find({
        include:getNestedAssociations(Issue)
    });
    
    
    
    //Recursively load all bested associtiaons
    function getNestedAssociations(_model) {
      const associations = [];
      for (const association of Object.keys(_model.associations)) {
        const model = _model.associations[association].target;
        const as = association;
        const include = getNestedAssociations(model);
        associations.push({
          model: model,
          as: as,
          ...(include && { include: include }),
        });
      }
      return associations;
    }
    
    0 讨论(0)
  • 2020-12-29 20:55

    Sequelize Docs: Nested Eager Loading

    Example

    Issue.find({
        include: [
            {
                model: Invite,
                include: [Group]
            }
        ]
    });
    
    0 讨论(0)
提交回复
热议问题