Objection.js-具有数据透视表的房地产

问题描述

我很难理解如何在objections.js中建立多对多关系的模型。

基本上,我有一个带有Users,Games和UsersScore表的应用程序。帐户可以在游戏中得分。

表是这样的:

用户表

  • id
  • 用户名

游戏桌

  • id
  • 名称

UsersScore表

  • id
  • userId
  • gameId
  • 得分

如何创建关系?

我想向登录用户显示所有游戏的列表 如果他在比赛中得分,那么他的得分

谢谢!

解决方法

这与异议文档中Join table extra properties概述的要求基本相同。您可以对其进行修改以创建usersgamesusers_games表。然后您的User模型可能看起来像这样:

class User extends Model {
  static get relationMappings() {
    return {
      relation: Model.ManyToManyRelation,modelClass: Game,join: {
        from: 'users.id',through: {
          from: 'users_games.user_id',to: 'users_games.game_id',extra: ['score']
        },to: 'game.id'
      }
    };
  }
}

在这里您可以看到我们在score连接表中添加了额外的users_games列。然后,我想您会获得类似以下内容的游戏列表:

const user = await User.query().findOne({ username: 'wombatsarefluffy' });
const games = await user.$relatedQuery('games');

有关如何构造迁移的示例,请参见文档页面。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...