Reputation: 2814
I have four models:
Category
Video
VideoCategory
VideoSchedule
With these relationships:
Category.belongsToMany(Video, { through: VideoCategory })
Video.belongsToMany(Category, { through: VideoCategory })
Video.hasOne(VideoSchedule)
VideoSchedule.belongsTo(Video)
I want to retrieve a list of categories for currently scheduled videos. I am very close, but Sequelize keeps giving me the attributes from the through table when all I want is the Category.id
and Category.name
. Here is my Sequelize:
Category.findAll({
attributes: ['id', 'name'],
raw: true,
group: 'Category.id',
order: 'Category.name',
include: [
{
model: Video,
attributes: [],
where: { active: true },
through: { attributes: [] },
include: [
{
model:
VideoSchedule,
attributes: [],
where: { site_id: 106 }
}
]
}
]
}).then(function(cats) { console.log(cats); } );
Here's a sample of the output I am getting:
{ id: 1,
name: 'Comedy',
'Videos.VideoCategory.category_id': 1,
'Videos.VideoCategory.video_id': 962 },
{ id: 2,
name: 'Drama',
'Videos.VideoCategory.category_id': 2,
'Videos.VideoCategory.video_id': 914 }
What I really want is just { id: 1, name: 'Comedy' }, { id: 2, name: 'Drama'}
. How do I get rid of the extra attributes from the through table? I tried using through: { attributes: [] }
in my include
statement, but to no avail. Just to be thorough, here is the SQL statement generated by Sequelize:
SELECT
`Category`.`id`,
`Category`.`name`,
`Videos.VideoCategory`.`category_id` AS `Videos.VideoCategory.category_id`,
`Videos.VideoCategory`.`video_id` AS `Videos.VideoCategory.video_id`
FROM
`categories` AS `Category`
INNER JOIN (`video_categories` AS `Videos.VideoCategory`
INNER JOIN `videos` AS `Videos` ON `Videos`.`id` = `Videos.VideoCategory`.`video_id`)
ON `Category`.`id` = `Videos.VideoCategory`.`category_id`
AND `Videos`.`active` = true
INNER JOIN `video_schedules` AS `Videos.VideoSchedule`
ON `Videos`.`id` = `Videos.VideoSchedule`.`video_id`
AND `Videos.VideoSchedule`.`site_id` = 106
GROUP BY Category.id
ORDER BY Category.name;
Any insight would be appreciated!
Upvotes: 1
Views: 3438
Reputation: 2814
For anyone else who runs into this, this is a bug in Sequelize. Looks like it will be fixed in 4.x, but not 3.x.
https://github.com/sequelize/sequelize/issues/5590
Upvotes: 3