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?
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 .
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.
You can turn off join table attributes by passing an empty attributes array to through like:
include: [{model: db.Artist, attributes: ['name'], through: {attributes: []}}]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With