Skip to content
关注公众号,获取新课通知

创建用户


数据表迁移文件

shell
npx sequelize migration:generate --name=user
js
"use strict";

module.exports = {
  up: (queryInterface, Sequelize) => {
    const { INTEGER, STRING, DATE, ENUM, TEXT } = Sequelize;
    return queryInterface.createTable("user", {
      id: {
        type: INTEGER(20),
        primaryKey: true,
        autoIncrement: true,
      },
      username: {
        type: STRING(30),
        allowNull: false,
        defaultValue: "",
        comment: "用户名",
        unique: true,
      },
      password: {
        type: STRING,
        allowNull: false,
        defaultValue: "",
        comment: "密码",
      },
      avatar: {
        type: STRING,
        allowNull: true,
        defaultValue: "",
        comment: "头像",
      },
      coin: {
        type: INTEGER,
        allowNull: false,
        defaultValue: 0,
        comment: "金币",
      },
      created_time: DATE,
      updated_time: DATE,
    });
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable("user");
  },
};

控制器:app/controller/admin/user.js

js
async create() {
        const { ctx, app } = this;
        await ctx.renderTemplate({
            title: "创建用户",
            tempType: "form",
            form: {
                // 提交地址
                action: "/admin/user",
                fields:[{
					label: "用户名",
					type: "text",
					name: "username",
					placeholder: "用户名",
				},{
					label: "密码",
					type: "text",
					name: "password",
					placeholder: "密码"
				},{
					label: "头像",
					type: "file",
					name: "avatar",
				},{
					label: "金币",
					type: "number",
					name: "coin",
					default: 0
				}]
            },
            // 新增成功跳转路径
            successUrl:"/admin/user"
        })
    }
	
	async save() {
        const { ctx, app } = this;

        // 参数验证
        ctx.validate({
            username: {
                type: 'string',
                required: true,
                desc: '用户名'
            },
            password: {
                type: 'string',
                required: true,
                desc: '密码'
            },
            avatar:{
                type:"string",
            },
            coin:{
                type:"int",
            }
        });
        let { username, password,avatar,coin } = ctx.request.body;

        // 验证用户是否已经存在
        if (await app.model.User.findOne({
            where: { username }
        })) {
            ctx.throw(400, '用户名已存在');
        }
        // 创建用户
        let user = await app.model.User.create({
            username,
            password,
            avatar,coin
        });
        if (!user) {
            ctx.throw(400, '创建用户失败');
        }
        ctx.apiSuccess(user);
    }

路由:app/router.js

js
router.get("/admin/user/create", controller.admin.user.create);
router.post("/admin/user", controller.admin.user.save);