2016-11-09 51 views
0

我爲節點項目使用Sequelize,但我在Sequelize方式中轉換查詢時遇到了一些麻煩。Sequelize - 對Sequelize方法的查詢

場景:我有2個表(用戶事件)與N:M關係通過UserEvent表。在UserEvent表中有is_creator屬性;我需要的是具有事件名稱,事件ID和is_creator字段的對象。

例子:

[{ 
    id: 1, 
    name: "Event", 
    is_creator: true 
}] 

下面是該查詢:

SELECT `Event`.`id`,`Event`.`name` as `Name`, `UserEvents`.`is_creator` AS `is_creator` FROM `Events` AS `Event` INNER JOIN (`UserEvents` INNER JOIN `Users` AS `Users` ON `Users`.`id` = `UserEvents`.`UserId`) ON `Event`.`id` = `UserEvents`.`EventId` AND `Users`.`id` = 1; 

不幸的是,我無法 「翻譯」 它Sequelize。

實際代碼:

var queryOptions: FindOptions = { 
      include: [ 
       { 
        model: db.User, 
        where: { 
         id: user.id 
        } 
       } 
      ], 
     }; 

查詢執行:

SELECT `Event`.`id`, `Event`.`uuid`, `Event`.`image`, `Event`.`name`, `Event`.`start_at`, `Event`.`end_at`, `Event`.`location`, `Event`.`description`, `Event`.`createdAt`, `Event`.`updatedAt`, `Users`.`id` AS `Users.id`, `Users`.`uuid` AS `Users.uuid`, `Users`.`email` AS `Users.email`, `Users`.`password` AS `Users.password`, `Users`.`firstName` AS `Users.firstName`, `Users`.`lastName` AS `Users.lastName`, `Users`.`activationCode` AS `Users.activationCode`, `Users`.`resetCode` AS `Users.resetCode`, `Users`.`active` AS `Users.active`, `Users`.`dob` AS `Users.dob`, `Users`.`image` AS `Users.image`, `Users`.`createdAt` AS `Users.createdAt`, `Users`.`updatedAt` AS `Users.updatedAt`, `Users.UserEvent`.`uuid` AS `Users.UserEvent.uuid`, `Users.UserEvent`.`is_creator` AS `Users.UserEvent.is_creator`, `Users.UserEvent`.`createdAt` AS `Users.UserEvent.createdAt`, `Users.UserEvent`.`updatedAt` AS `Users.UserEvent.updatedAt`, `Users.UserEvent`.`UserId` AS `Users.UserEvent.UserId`, `Users.UserEvent`.`EventId` AS `Users.UserEvent.EventId` FROM `Events` AS `Event` INNER JOIN (`UserEvents` AS `Users.UserEvent` INNER JOIN `Users` AS `Users` ON `Users`.`id` = `Users.UserEvent`.`UserId`) ON `Event`.`id` = `Users.UserEvent`.`EventId` AND `Users`.`id` = 1; 

預先感謝您的合作!

回答

0

是否要限制查詢返回的列數?您可以查看attributes選項。您可以指定所需的表格字段。

例如,如果您需要用戶的ID,電子郵件和名字,可以用這種方式指定它。

var queryOptions: FindOptions = { 
     include: [ 
      { 
       model: db.User, 
       where: { 
        id: user.id 
       }, 
       attributes: ['id', 'email', 'firstName'] 
      } 
     ], 
    }; 

您可以類似地爲UserEvents表添加屬性選項。

PS:我目前沒有足夠的聲望來對問題添加評論。否則,我會這樣做。