简体   繁体   中英

in nested eager loading sequelize query, fetch only some attributes

Here's my query for fetching shows from a database, plus its associated venue and bands. I really only want to get the names of the bands and venue. ( name is the field in both of those tables.) The code below is fetching the whole record, though, and not just the field that I want.

const getAllShows = async (req, res) => {
    try {
        const shows = await Show.findAll({
            include: [
                { model: User, as: 'bands', through: { attributes: ['name'] } }, 
                { model: Venue, through: { attributes: ['name'] }}
            ],
        });
        res.status(200).send(shows); 
    }
    catch(err) {
        res.send(400);
    }
}

The attributes is misplaced - it doesn't belong under the through (btw, depending on your associations, you may not even need through ).

Try changing like this:

{ model: User, as: 'bands', attributes: ['name']},

You might also consider field aliases, like this:

{ model: User, as: 'bands', attributes: [['name', 'band_name']]},

hth

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