對(duì)用戶表新增字段
$ sequelize migration:create --name add-avatar-to-user
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('Users', 'avatar', {
type: Sequelize.STRING
})
},
async down(queryInterface, Sequelize) {
await queryInterface.removeColum('Users', 'avatar')
}
};
$ sequelize db:migrate
最后記得在 User 模型中 添加 avatar 字段
種子數(shù)據(jù)
$ sequelize seed:generate --name user
await queryInterface.bulkInsert('Users', [{
email: 'admin@ims.com',
username: 'admin',
password: '123456',
nickname: '管理員',
sex: 2,
role: 100,
createdAt: new Date(),
updatedAt: new Date()
},
{
email: 'abc@ims.com',
username: 'abc',
password: '123456',
nickname: '管理員',
sex: 2,
role: 0,
createdAt: new Date(),
updatedAt: new Date()
}], {});
$ sequelize db:seed --seed ./seeders/20241029052732-user.js
自定義驗(yàn)證
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
User.init({
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: { msg: "必須填寫(xiě)" },
notEmpty: { msg: "不能為空字符串" },
isEmail: { msg: "格式不正確" },
async isUnique(value) {
const user = await User.findOne({ where: { email: value } })
if (user) {
throw new Error("郵箱已存在");
}
}
}
},
username: DataTypes.STRING,
password: DataTypes.STRING,
nickname: DataTypes.STRING,
sex: DataTypes.TINYINT,
company: DataTypes.STRING,
introduce: DataTypes.TEXT,
role: DataTypes.TINYINT,
avatar: DataTypes.STRING
}, {
sequelize,
modelName: 'User',
});
return User;
};