使用 include 时,Sequelize 在结果中包含引用 table 行

Sequelize includes reference table row in result when using include

我定义了 TrackArtist 模型,关联如下:

db.Track.belongsToMany(db.Artist, {through: 'TracksArtists'});
db.Artist.belongsToMany(db.Track, {through: 'TracksArtists'});

我想搜索曲目并在结果中包含 Artist.name:

db.Track
    findAll({ 
        attributes: ['title','year'], 
        where: { title: { like: '%' + string + '%' } },
        include: [{model: db.Artist, attributes: ['name']}]
    })
    .complete(function(err, tracks){ /*...*/});

但是,Sequelize 还在结果中包含来自 TracksArtists 参考 table 的一行:

[{"title":"Nightcall","year":2010,"Artists":[{"name":"Kavinsky","TracksArtists":{"createdAt":"2015-01-13T18:41:31.850Z","updatedAt":"2015-01-13T18:41:31.850Z","ArtistId":1,"TrackId":1}}]}]

这是不必要的。我怎样才能避免 return 来自 TracksArtists 的信息,而不必自己删除它?

您可以通过将空属性数组传递给以下方式来关闭加入 table 属性:

include: [{model: db.Artist, attributes: ['name'], through: {attributes: []}}]

我定义了 FaqArtist 模型,关联如下:

Faq.belongsToMany(Version, { through: FaqVersion, foreignKey: 'faqId' });
Version.belongsToMany(Faq, { through: FaqVersion, foreignKey: 'verId' });

我遇到了和作者一样的问题,不过我补充一下:

models.Version.findAll({
  raw: true,
  attributes: ['id', 'version'],
  include: [{
    model: models.Faq,
    attributes: [],
    through: { attributes: [] },
    where: {
    id: faq.id
    }
 }]
})

但是,Sequelize 在结果中还包含来自 FaqVersion 参考 table 的一行:

Faqs.FaqVersion.createdAt:"2017-01-10T05:22:06.000Z",
Faqs.FaqVersion.faqId:2,
Faqs.FaqVersion.id:3,
Faqs.FaqVersion.updatedAt:"2017-01-10T05:22:06.000Z",
Faqs.FaqVersion.verId:2,
id:2,
version:"5.2.6"

我觉得through不行

只需使用如下语法:

include: [
            {
                model: ModelName,
                through: {attributes: []}
            }
    ]