在feather-sequelize中建立连接表中附加属性的belongsToMany关系,可以通过以下步骤实现:
npm install feathers-sequelize sequelize --save
// user.model.js
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const { DataTypes } = sequelizeClient;
const User = sequelizeClient.define('user', {
// 用户模型的属性
name: {
type: DataTypes.STRING,
allowNull: false
},
// ...
}, {});
User.associate = function (models) {
User.belongsToMany(models.role, {
through: 'user_role',
foreignKey: 'userId',
otherKey: 'roleId'
});
};
return User;
};
// role.model.js
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const { DataTypes } = sequelizeClient;
const Role = sequelizeClient.define('role', {
// 角色模型的属性
name: {
type: DataTypes.STRING,
allowNull: false
},
// ...
}, {});
Role.associate = function (models) {
Role.belongsToMany(models.user, {
through: 'user_role',
foreignKey: 'roleId',
otherKey: 'userId'
});
};
return Role;
};
// user-role.model.js
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const { DataTypes } = sequelizeClient;
const UserRole = sequelizeClient.define('user_role', {
isPrimary: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
}
}, {});
return UserRole;
};
// user.service.js
const { Service } = require('feathers-sequelize');
exports.User = class User extends Service {
constructor(options, app) {
super(options);
}
};
// role.service.js
const { Service } = require('feathers-sequelize');
exports.Role = class Role extends Service {
constructor(options, app) {
super(options);
}
};
// user-role.service.js
const { Service } = require('feathers-sequelize');
exports.UserRole = class UserRole extends Service {
constructor(options, app) {
super(options);
}
};
const feathers = require('@feathersjs/feathers');
const express = require('@feathersjs/express');
const Sequelize = require('sequelize');
const { User, Role, UserRole } = require('./services');
const app = express(feathers());
// 初始化Sequelize实例
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mysql',
host: 'localhost'
});
// 将Sequelize实例设置为app的属性
app.set('sequelizeClient', sequelize);
// 初始化模型
app.use('/users', new User({}, app));
app.use('/roles', new Role({}, app));
app.use('/user-roles', new UserRole({}, app));
// 启动应用程序
app.listen(3030).on('listening', () =>
console.log('Feathers server listening on localhost:3030')
);
现在,我们已经成功建立了在feather-sequelize中连接表中附加属性的belongsToMany关系。您可以根据需要在服务中添加其他方法和逻辑来处理这些关系。
领取专属 10元无门槛券
手把手带您无忧上云