Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize includes reference table row in result when using include

Tags:

sequelize.js

I have Track and Artist models defined, with association as follows:

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

I want to search for Tracks and include Artist.name in the results:

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

However, Sequelize also includes a row from TracksArtists reference table in the results:

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

which is unnecessary. How can I make it not to return info from TracksArtists, instead of having to remove it on my own?

like image 877
user1205255 Avatar asked Jan 13 '15 18:01

user1205255


People also ask

How do I use includes in Sequelize?

To wrap up, include takes an array of objects. These objects are queries of their own, essentially just Sequelize queries within our main query. Inside each include query we specify the associated model , narrow our results with where , and alias our returned rows with as .

How do you include two models in Sequelize?

Your solution, along with using include: {all:true} in my findAll query, did the trick. instead of using include: {all:true} in findAll you can use include: {model: models. User, as: 'createdByUser'} , etc. Be sure to use as: in all associations to the same model in your Sequelize model declaration.


2 Answers

You can turn off join table attributes by passing an empty attributes array to through like:

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

like image 194
Mick Hansen Avatar answered Sep 22 '22 17:09

Mick Hansen


I have Faq and Artist models defined, with association as follows:

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

I encountered the same problem with the author, but i add:

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

However, Sequelize also includes a row from FaqVersion reference table in the results:

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"

I think through does not work

like image 36
jiapeiyang Avatar answered Sep 23 '22 17:09

jiapeiyang