Sequelize包含使用include时的结果中的引用表行

时间:2015-01-13 18:58:44

标签: sequelize.js

我定义了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参考表的一行:

[{"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}}]}]

这是不必要的。我怎样才能让它不从TracksArtists返回信息,而不是自己删除它?

3 个答案:

答案 0 :(得分:11)

您可以通过将空属性数组传递到以下来关闭连接表属性:

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

答案 1 :(得分:1)

我定义了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参考表的一行:

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不起作用

答案 2 :(得分:0)

只需使用这样的语法:

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