从多对多关系中获取结果

问题描述 投票:0回答:1

我正在尝试从GraphQL解析器中的多对多关系(用户和角色之间)获得结果,但是我对Sequelize还是很陌生,不了解查询模型的正确方法。

这是我的用户模型:

module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('users', {
	id: {
		type: DataTypes.INTEGER(10).UNSIGNED,
		allowNull: false,
		primaryKey: true,
		autoIncrement: true
	},
	name: {
		type: DataTypes.STRING(50),
		allowNull: false
	},
	surname: {
		type: DataTypes.STRING(50),
		allowNull: false
	},
	email: {
		type: DataTypes.STRING(256),
		allowNull: false
	}
}, {
	tableName: 'users',
	timestamps: false,
});

User.associate = function (models) {
	User.belongsToMany(models.roles, {as: 'UserRoles', through: 'users_roles', foreignKey: 'role_id'})
};

return User
};

这是我的榜样:

module.exports = function(sequelize, DataTypes) {
var Role = sequelize.define('roles', {
	id: {
		type: DataTypes.INTEGER(10).UNSIGNED,
		allowNull: false,
		primaryKey: true,
		autoIncrement: true
	},
	name: {
		type: DataTypes.STRING(50),
		allowNull: false
	}
}, {
	tableName: 'roles',
	timestamps: false,
});

Role.associate = function (models) {
	Role.belongsToMany(models.users, {through: 'users_roles', foreignKey: 'role_id'})
};

return Role
};

这是我的联接表模型:

module.exports = function(sequelize, DataTypes) {
	return sequelize.define('users_roles', {
		id: {
			type: DataTypes.INTEGER(10).UNSIGNED,
			allowNull: false,
			primaryKey: true,
			autoIncrement: true
		},
		user_id: {
			type: DataTypes.INTEGER(10).UNSIGNED,
			allowNull: false,
			references: {
				model: 'users',
				key: 'id'
			}
		},
		role_id: {
			type: DataTypes.INTEGER(10).UNSIGNED,
			allowNull: false,
			references: {
				model: 'roles',
				key: 'id'
			}
		}
	}, {
		tableName: 'users_roles',
		timestamps: false
	});
};

到目前为止,这是我的GraphQL定义:

import { gql } from 'apollo-server-express'
import * as db from '../database'

export const typeDefs = gql`
    extend type Query {
        users: [User]
        user(id: ID!): User
    }
    type User {
        id: ID!
        email: String
        name: String
        surname: String
        roles: [String]
    }
`

export const resolvers = {
    Query: {
        users: async () => db.users.findAll(),
        user: async (obj, args, context, info) => db.users.findByPk(args.id),
    },
    User: {
        roles: async (obj, args, context, info) => db.roles.findAll(), // wrong!!
    }
}

所以基本上,我的问题是我不知道如何编写查询以获取分配给一个用户的所有角色的列表。

我最后想要得到的(如用户类型定义所示)是一个包含所有角色名称的字符串数组。

javascript node.js graphql sequelize.js apollo-server
1个回答
0
投票

鉴于我们已经为另一个模型正确定义了UserHasMany关系的BelongsToMany实例,我们可以通过在实例上调用适当的方法来获取关联模型的数组。方法名称通常为get[PLURAL_NAME_OF_MODEL](即getRoles),但是由于您为关系提供了as选项,因此该方法应为getUserRoles。因此,只需调用:

return obj.getUserRoles()

注意,您也可以在根解析器中eager load相关的模型。在这种情况下,如果roles选项与您的字段名称相匹配(即为as),则可以完全省略roles的解析器。如果您渴望加载关联的模型,但as与您的字段名称不匹配(例如在这种情况下),则可以返回obj[WHATEVER_THE_AS_OPTION_IS](即obj.UserRoles)。

© www.soinside.com 2019 - 2024. All rights reserved.