简体   繁体   中英

SEQUELIZE - How to Get All Assosciated Objects?

I have a many to many association like this:

Squad.belongsToMany(Member, {through: Membership});
Member.belongsToMany(Squad, {through: Membership});

How do I find all the Squads, and for each squad, show me the squad name and an array with the Members that each squad has associated with it?

UPDATED WITH WHAT I'VE BEEN TRYING AND WHAT RESULTS I GET:

I've been trying things like this:

Squad.findAll({
    include: [{
        model: Member,
        required: true
    }]
}).then(squads => {
    // The rest of your logics here...
});

Here's a sample of what I get:

  { id: 3,
    name: 'Knicks',
    city: 'NYC',
    state: 'NY',
    'members.id': 3,
    'members.name': 'Carmelo',
    'members.city': 'NYC'
  },

  { id: 3,
    name: 'Knicks',
    city: 'NYC',
    state: 'NY',
    'members.id': 2,
    'members.name': 'Penny',
    'members.city': 'Orlando',
    'members.state': 'Florida'
  }

But what I want is not multiples of the same object and individual member info. I'm trying to get something more like this:

{ id: 2, name: 'Lakers', members: [ memberInfo, memberInfo, memberInfo] }

Is there a way to do that?

Assuming that you modeled your relations correctly, then you should be able to do something like

Squad.findAll({
    include: [{
        model: Member,
        required: true
    }]
}).then(squads => {
    // The rest of your logics here...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM