简体   繁体   English

在嵌套预加载 sequelize 查询中,只获取一些属性

[英]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. name是这两个表中的字段。)不过,下面的代码正在获取整个记录,而不仅仅是我想要的字段。

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 ). attributes放错了地方——它不属于through (顺便说一句,根据你的关联,你甚至可能不需要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 hth

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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