import { Application } from 'egg';
import * as uuidv4 from 'uuid/v4';
/** 用户资料表,修改邮箱和手机号时,需要同步到userAuth表 */
export default function(app: Application) {
const { STRING, BOOLEAN, DATE, UUID, ARRAY } = app.Sequelize;
const tableName = 'user';
const User = app.model.define(
tableName,
{
id: {
type: UUID,
unique: true,
primaryKey: true,
allowNull: false,
defaultValue: () => {
return uuidv4().replace(/-/g, '');
},
},
username: {
type: STRING(32),
unique: true,
allowNull: false,
comment: '用户名',
},
password: {
type: STRING(255),
allowNull: false,
comment: '密码',
},
email: {
type: STRING(64),
unique: true,
allowNull: true,
comment: '邮箱地址',
},
phone: {
type: STRING(20),
unique: true,
allowNull: true,
comment: '手机号码',
},
avatar: {
type: STRING(150),
allowNull: true,
comment: '头像',
},
alias: {
type: STRING(30),
comment: '别名',
},
realName: {
type: STRING(30),
allowNull: true,
comment: '真实姓名',
},
signature: {
type: STRING(255),
allowNull: true,
comment: '签名',
},
status: {
type: BOOLEAN,
allowNull: false,
defaultValue: 1,
comment: '用户状态: 1 正常; 0 禁用',
},
lastActivedAt: DATE,
createdAt: DATE,
updatedAt: DATE,
},
{
tableName,
comment: '用户表',
timestamps: true,
underscored: false,
}
);
class UserModal extends User {
id: string;
username: string;
email: string;
phone: string;
avatar: string;
alias: string;
realName: string;
signature: string;
status: boolean;
roles: any[];
lastActivedAt: number;
static associate() {
app.model.User.hasMany(app.model.UserAuth, { as: 'userAuths', sourceKey: 'id', foreignKey: 'userId' });
app.model.User.belongsToMany(app.model.Role, { as: 'roles', through: app.model.UserRoleRelation, foreignKey: 'userId' });
}
}
return UserModal;
}