使用关联方法使用sequelize orm

时间:2017-05-30 07:02:53

标签: ecmascript-6

使用关联方法的sequelize orm 我正在使用Node和Sequelize ORM处理API。正在使用的数据库是MYSQL。我在下面的代码中使用了belongsTo()。 每个用户都有喜欢的游戏。使用user_Id为每个用户获取最喜欢的游戏。 我得到了一个续集的结果,但除了另一个。

this.userFavoriteGameModel = require("../entity/favorite_game")(this.database, this.Sequelize);
this.gameModel = require("../entity/game")(this.database, this.Sequelize);

 //Fecth user favorite game list
    favoriteGameList(name, cb) {
        let self = this;
        var user_Id = 5;
        self.userFavoriteGameModel.belongsTo(self.gameModel, {
            as: "game_detail",
            foreignKey: 'game_Id'
        });
        self.userFavoriteGameModel.findAll({
            attributes: [
                'game_Id'
            ],
            where: {
                user_id: user_Id
            },
            include: [{
                model: self.gameModel,
                as: 'game_detail',
                attributes: ["game_Title", "game_Subtitle", "icon", "game_Rating"]
            }],
            group: ['game_Id']
        }).then(function (result) {
            cb(result);
            let obj1 = result;
            let obj2 = Object.assign({}, obj1);
            console.log(JSON.stringify(obj2));
        }, function (err) {
            console.log('An error occurred while creating the table:', err);
            cb(err);
        });
    }
}

[
  {
    "dataObject": [
      {
        "game_Id": 57,
        "game_detail": {
          "game_Title": "battlefield1",
          "game_Subtitle": "Limited edition",
          "icon": "image.png",
          "game_Rating": 2
        }
      },
      {
        "game_Id": 58,
        "game_detail": {
          "game_Title": "battlefield2",
          "game_Subtitle": "Limited edition",
          "icon": "image.png",
          "game_Rating": 1
        }
      }
    ]
  }
]

Excepting Result : 

[
  {
    "dataObject": [
      {
         "game_Id": 57,
          "game_Title": "battlefield1",
          "game_Subtitle": "Limited edition",
          "icon": "image.png",
          "game_Rating": 2
      },
      {
          "game_Id": 58,
          "game_Title": "battlefield2",
          "game_Subtitle": "Limited edition",
          "icon": "image.png",
          "game_Rating": 1
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:0)

sequelize orm使嵌套json成为hasMany属于其他关系的结果如果你不想将它作为最终结果你可以得到续集结果然后手动像你想要的那样:

var finalResult={}
for(var key in object){
    if(typeof object['key'] == 'object'){
         var parent=object['key']
         for(var childKey in parent){
                     finalresult['childKey']=parent['childKey']
         }
     }else{
        finalresult['key']=object['key']
     }
 }