如何通过表属性删除?

时间:2016-08-13 08:27:35

标签: sequelize.js

我有四种模式:

Category
Video
VideoCategory
VideoSchedule

有了这些关系:

Category.belongsToMany(Video, { through: VideoCategory })
Video.belongsToMany(Category, { through: VideoCategory })
Video.hasOne(VideoSchedule)
VideoSchedule.belongsTo(Video)

我想检索当前预定视频的类别列表。我非常接近,但是当我想要的只是Category.idCategory.name时,Sequelize会一直向我提供表格中的属性。这是我的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); } );

这是我得到的输出样本:

{ 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 }

我真正想要的只是{ id: 1, name: 'Comedy' }, { id: 2, name: 'Drama'}。如何摆脱直通表中的额外属性?我尝试在through: { attributes: [] }声明中使用include,但无济于事。为了彻底,这是Sequelize生成的SQL语句:

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;

任何见解都将受到赞赏!

1 个答案:

答案 0 :(得分:3)

对于遇到此问题的其他人来说,这是Sequelize中的一个错误。看起来它将在4.x中修复,但不是3.x。

https://github.com/sequelize/sequelize/issues/5590