【问题标题】:Bookshelf.js belongsToMany query with wrong columnBookshelf.js belongsToMany 查询列错误
【发布时间】:2017-01-29 22:17:45
【问题描述】:

我正在努力处理我的书架模型中的关系。我要做的是创建包含 4 个表的架构:

  • 用户
  • 角色
  • 特权
  • privileges_roles

他们之间的关系是这样的:

用户 manyTOone roles manyTOone privileges_roles oneTOmany privileges

我很容易通过以下方式实现权限和角色之间的关系:

权限

class Privileges {
    constructor() {
        this.model = bookshelf.Model.extend({
            tableName: 'privileges',
            roles: function () {
                return this.belongsToMany(Roles.model).through(PrivilegeRole.model);
            }
        });
    };
}

角色

class Roles {
    constructor() {
        this.model = bookshelf.Model.extend({
          tableName: 'roles',
          privileges: function() {
              return this.belongsToMany(Privileges.model).through(PrivilegeRole.model);
          },
          users: function() {
              return this.hasMany(Users.model);
          }
        });
    };
}

PrivilegeRole

class PrivilegeRole {
    constructor() {
        this.model = bookshelf.Model.extend({
          tableName: 'privileges_roles',
          role: function() {
              return this.belongsTo(Roles.model);
          },
          privileges: function() {
              return this.belongsTo(Privileges.model);
          }
        });
    };
}

那些工作真的很好。不幸的是,当我尝试从 User 模型中获取 Privileges 时,它会一直插入 id 而不是 role_id 进行查询。

class Users {
    constructor() {
        this.model = bookshelf.Model.extend({
            tableName: 'users',
            role: function () {
                return this.belongsTo(Role.model);
            },
            privileges: function () {
                // return this.belongsToMany(Privileges.model).through(PrivilegeRole.model);
                return this.belongsToMany(Privileges.model, 'privileges_roles', 'role_id', 'privilege_id', 'role_id');
            }
        });
    };
}

所以最后无论我做什么,书架都会创建这样的查询:

选择privileges.*, privileges_roles.id_pivot_id, privileges_roles.role_id 作为_pivot_role_id, privileges_roles.privilege_id as _pivot_privilege_id 来自 privileges 内连接 privileges_roles on privileges_roles.privilege_id = privileges.id 在哪里 privileges_roles.role_id 在(1)

而不是(3)中的role_id,就像它在获取的记录中一样。

【问题讨论】:

    标签: javascript mysql bookshelf.js


    【解决方案1】:

    好吧,我终于找到了解决方案。而不是以前使用的:

    privileges: function () {
                    return this.belongsToMany(Privileges.model, 'privileges_roles', 'role_id', 'privilege_id', 'role_id');
                }
    

    我不得不简单地使用:

    privileges: function () {
                    return this.belongsToMany(Privileges.model).through(PrivilegeRole.model, 'role_id', 'privilege_id', 'role_id');
                }
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多