Sails.js + Waterline:通过关联实现多对多

2024-04-08

我是 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'
        }
    }
}

但是当我尝试访问控制器中的角色属性时

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

这返回

[]

And

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

returns

{"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');
    }           
});
...

也许这对某人有用=)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Sails.js + Waterline:通过关联实现多对多 的相关文章

随机推荐