src/app/model 里面定义数据库模型
sequelize.define 定义模型
sequelize.define('model_name',{filed:value})
创建表
- 首先定义模型: model
- 然后同步:model.sync()
- 创建表会自动创建主键,默认为 id,自增长
Object.keys(app)
[
'_events',
'_eventsCount',
'_maxListeners',
'subdomainOffset',
'proxyIpHeader',
'maxIpsCount',
'middleware',
'context',
'request',
'response',
'timing',
'options',
'_options',
'console',
'BaseContextClass',
'Controller',
'Service',
'lifecycle',
'loader',
'ContextCookies',
'ContextLogger',
'ContextHttpClient',
'HttpClient',
'messenger',
'_unhandledRejectionHandler',
'cluster',
'Subscription',
'BaseHookClass',
'Boot',
'safeCurl',
'ScheduleStrategy',
'TimerScheduleStrategy',
'schedule',
'LogRotator',
'watcher',
'Sequelize'
]
Model
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;
}
Model属性和方法
https://sequelize.org/master/class/lib/model.js~Model.html
instance.field
// is the same as
instance.get('field')
// is the same as
instance.getDataValue('field')