Objection.js 中的多对多关系

Many-to-Many-to-Many relationship in Objection.js

我有一个用户可以拥有多个平台的项目。这些平台可以有很多密码。目前我有以下数据库结构:

我正在尝试使用预先加载来获取以下对象:

{
    "id": 1,
    "username": "Keith",
    "platforms": [
        {
            "id": 1,
            "name": "Jira",
            "passwords": [
                {
                    "id": 1,
                    "password": "hash"
                },
                {
                    "id": 2,
                    "password": "otherhash"
                }
            ]
        },
        {
            "id": 2,
            "name": "Confluence",
            "passwords": [
                {
                    "id": 3,
                    "password": "anotherhash"
                },
                {
                    "id": 4,
                    "password": "anotherone"
                }
            ]
        }
    ]
}

我花了几个小时想不通。我如何定义关系以获得这种结构?这可能吗?

据我所知,如果不为该 3 向连接创建自己的模型是不可能的 table。

所以模型看起来像这样:

class User extends objection.Model {
  static get tableName() {
    return 'user';
  }

  static get relationMappings() { 
    return {
      platformPasswords: {
        relation: Model.HasManyRelation,
        modelClass: UserPlatformPassword,
        join: {
          from: 'user.id',
          to: 'user_platform_password.user_id'
        }
      }
    }
  }
}

class Platform extends objection.Model {
  static get tableName() {
    return 'platform';
  }
}

class Password extends objection.Model {
  static get tableName() {
    return 'password';
  }
}

class UserPlatformPassword extends objection.Model {
  static get tableName() {
    return 'user_platform_password';
  }

  static get relationMappings() { 
    return {
      password: {
        relation: Model.HasOne,
        modelClass: Password,
        join: {
          from: 'user_platform_password.password_id',
          to: 'password.id'
        }
      },
      platform: {
        relation: Model.HasOne,
        modelClass: Platform,
        join: {
          from: 'user_platform_password.platform_id',
          to: 'platform.id'
        }
      }
    }
  }
}

也许还有一些其他方法可以对这些关系进行建模,至少以它们在进行急切选择时起作用的方式,但我很难理解它在您想插入 /插入嵌套数据,其中多个关系处理同一连接的不同字段 table.