codememo

Sequelize와 중첩 관계

tipmemo 2023. 9. 15. 21:02
반응형

Sequelize와 중첩 관계

Sequelize with Node + MySQL을 사용하고 있습니다.

저는 이와 유사한 모델 구조를 가지고 있습니다.

// models:
var Group, Issue, Invite;

// many Issues per Group
Group.hasMany(Issue);
Issue.belongsTo(Group);

// Groups can invite other Groups to work on their Issues
Issue.hasMany(Invite, {foreignKey: groupId});
Invite.belongsTo(Issue, {foreignKey: groupId});
Group.hasMany(Invite, {foreignKey: inviteeId});
Invite.belongsTo(Group, {foreignKey: inviteeId});

// given an Issue id, include all Invites + invited Groups (inviteeId) - But how?
var query = {
    where: {id: ...}, 
    include: ???
};
Issue.find(query).complete(function(err, issue) {
    var invites = issue.invites;
    var firstInvitedGroup = issue.invites[0].group;
    // ...
});

가능한 일입니까?가능한 해결 방법은 무엇입니까?감사해요!

Sequelize Docs: Nested Eager Loading

Issue.find({
    include: [
        {
            model: Invite,
            include: [Group]
        }
    ]
});

모든 중첩 연결을 빨리 로드하려면 이 함수를 사용합니다.

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;
}

모든 희망을 잃은 후, 저는 마지막으로 효과가 있는 한 번의 랜덤 히트 snd를 시도했습니다.배열이 비어 있는 특성만 전송하면 결과에 포함되지 않습니다.

{
    model: User,
    as: 'users',
    attributes: [],  // This will work//
    where: {
      user_id: 1
    }
  }

언급URL : https://stackoverflow.com/questions/24282990/nested-relations-with-sequelize

반응형