orm - Sails.js + 水线 : Many-to-Many through association

标签 orm many-to-many sails.js waterline

我是 Sails.js (v0.10.5) 和 Waterline ORM 的新手。我在数据库中有 3 个表:用户(id,名称),角色(id,别名)和连接表 users_roles(user_id,role_id)。重要的是不要更改数据库中的表名和字段名。我希望策略实体成为用户和角色之间的连接实体。下面是一些映射代码:

//User.js
module.exports = {
    tableName: 'users',
    autoCreatedAt: false,
    autoUpdatedAt: false,
    attributes: {
        id: {
            type: 'integer',
            required: true
        },
        name: {
            type: 'string'
        },
        roles: {
            collection: 'role',
            via: 'users',
            through: 'policy'
        },
    }
}

//Role.js
module.exports = {
    tableName: "roles",
    autoCreatedAt: false,
    autoUpdatedAt: false,
    attributes: {
        id: {
            type: 'integer',
            required: true
        },
        alias: {
            type: 'string',
            required: true
        },
        users: {
            collection: 'user',
            via: 'roles',
            through: 'policy'
        }
    }
}

//Policy.js
module.exports = {
    tableName: "users_roles",
    tables: ['users', 'roles'],
    junctionTable: true,
    autoCreatedAt: false,
    autoUpdatedAt: false,
    attributes: {
        user: {
            columnName: 'user',
            type: 'integer',
            foreignKey: true,
            references: 'user',
            on: 'id',
            via: 'role',
            groupBy: 'user'
        },
        roles: {
            columnName: 'role',
            type: 'integer',
            foreignKey: true,
            references: 'role',
            on: 'id',
            via: 'user',
            groupBy: 'role'
        }
    }
}

但是当我尝试访问 Controller 中的角色属性时
User.findOne({id: 1}).populate('roles').exec(function(err, user) {
    console.log(JSON.stringify(user.roles));
});

这返回
[]


User.findOne({id: 1}).populate('roles').exec(function(err, user) {
    console.log(JSON.stringify(user));
});

返回
{"id":1,"name":"test", "roles":[]}

我检查了两次该用户、角色和它们之间的关联存在于数据库中。我的错误是什么?

最佳答案

我找到了解决这个问题的方法。这不是我真正想要的,但它有效。
第一:加入实体:

//Policy.js
module.exports = {
    tableName: "users_roles",
    autoPK: false,
    attributes: {
        id: {
            type: 'integer',
            primaryKey: true,
            autoIncrement: true,
        },
        user: {
            columnName: 'user_id',
            model: 'user'
        },
        role: {
            columnName: 'role_id',
            model: 'role'
        }
    },
    //tricky method to get all users for specified role_id
    //or to get all roles for specified user_id
    get: function(id, modificator, cb) {
        var fields = ['user', 'role'];
        if (fields.indexOf(modificator) < 0) {
            cb(new Error('No such modificator in Policy.get()'), null);
        }
        var inversedField = fields[(fields.indexOf(modificator) + 1) % 2];
        var condition = {};
        condition[inversedField] = id;
        this.find(condition).populate(modificator).exec(function(err, policies) {
            if (err) {
                cb(err, null);
                return;
            }
            var result = [];
            policies.forEach(function(policy) {
                result.push(policy[modificator]);
            });
            cb(null, result);
            return;
        });
    }
}

如您所见,我向该实体添加了 ID 字段(也向数据库表 users_roles 添加了 ID 字段),因此这不是一个很好的解决方案。
//User.js
module.exports = {
    tableName: 'users',
    autoPK: false,
    attributes: {
        id: {
            type: 'integer',
            primaryKey: true,
            autoIncrement: true,
            unique: true,
        },
        name: {
            type: 'string'
        },
        policies: {
            collection: 'policy',
            via: 'user'
        }
    }
}

和角色实体:
//Role.js
module.exports = {
    tableName: 'roles',
    autoPK: false,
    attributes: {
        id: {
            type: 'integer',
            primaryKey: true,
            autoIncrement: true,
        },
        alias: {
            type: 'string',
            required: true,
            unique: true,
        },
        policies: {
            collection: 'policy',
            via: 'role'
        }
    }
}

这就是我获取指定 user_id 的所有角色的方式:
...
id = req.session.me.id; //user_id here
Policy.get(id, 'role', function(err, roles) {
    var isAdmin = false;
    roles.forEach(function(role) {
        isAdmin |= (role.id === 1);
    });
    if (isAdmin) {
        next(null);
        return;
    } else {
        return res.redirect('/login');
    }           
});
...

也许它对某人有用=)

关于orm - Sails.js + 水线 : Many-to-Many through association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27013077/

相关文章:

用于 REST 的 Node.js Express? Express 中有 Controller 吗?

node.js - SailsJS - 蓝图关联 "add to"

sails.js - Sailsjs 一对多空结果

asp.net - 使用 ASP.Net 编辑表格 - Quick 'n Dirty

java - 多对多hibernate xml配置

java - 以可联合的顺序 hibernate ManyToMany

php - Doctrine 2 - 记录多对多关系中的更改

java - 2 个 JPA 实体在同一张表上

java - 具有嵌入式对象的实体的 Hibernate 标准

c# - 插入新实体而不创建子实体(如果存在)