【问题标题】:How to perform join in sails JS如何在sails JS中执行join
【发布时间】:2015-12-11 08:35:43
【问题描述】:

我有表格的文件

挑战:

{
  "name": "challenge by abdul",
  "created_user_id": "1",
  "game_id": "123",
  "platform_id": "9857",
  "amount": 30

}

game: 
{
  "_id": "auto_generated",
  "name": "NFS",
  "version": "3",
}



platform:
{
  "_id": "auto_generated",
  "name": "ps2",
  "version": "sami"
}

我想在sails 中执行连接查询并希望得到以下格式的结果

{
  "name": "challenge by abdul",
  "created_user_id": "1",
  "game_id": "123",
  "game_name":"NFS",
  "platform_name": "ps2",
  "platform_id": "9857",
  "amount": 30

}

【问题讨论】:

  • 您是否阅读过 models 上的 Sails 文档,尤其是 associations 部分?使用 ORM,您通常不会获得像您所描述的对象那样的对象,但您会获得具有 gameplatform 和可能的 user 属性的 Challenge 模型对象本身包含您想要的信息的对象。查看文档,看看您是否还有关于如何构建模型和查询的问题。

标签: json sails.js sails-mongo


【解决方案1】:

Sails 中没有加入但填充。因此,您需要在模型之间建立关联并填充它们。示例:

// api/models/Platform.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },

    version: {
      type: 'string'
    },

    game: {
      model: 'Game',
      via: 'platform'
    }
  }
};

// api/models/Game.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },

    version: {
      type: 'string'
    },

    platform: {
      model: 'Platform',
      via: 'game'
    }
  }
};

然后你可以编写如下代码:

// api/controllers/AnyController.js
module.exports = {
  index: function(req, res) {
    Game
      .findOne({name: 'MY_GAME'})
      .populate('platform')
      .then(function(game) {
        console.log(game); // Game model
        console.log(game.platform); // Platform model
        return game;
      })
      .then(res.ok)
      .catch(res.negotiate);
  }
};

【讨论】:

  • 我需要查询挑战模型
  • 这是“如何将模型合并为一个”的示例。您可以根据自己的需要调整示例。
  • 我想从游戏结果中写入 where 条件,比如 .populate('platform', {where: {id:game_id}}),对吗?
  • 是的。你可以试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 2023-01-09
  • 2021-02-23
  • 2018-12-25
  • 1970-01-01
  • 2015-10-07
相关资源
最近更新 更多