定义模型生成数据表
1. 数据库配置
```js
import { Sequelize, DataTypes } from 'sequelize';
// 创建一个 Sequelize 实例,连接到 SQLite 数据库。
export const sequelize = new Sequelize('test', 'sa', "123456", {
host: 'localhost',
dialect: 'sqlite',
storage: './blog.db'
});
```
2. 模型定义
```js
import { DataTypes } from 'sequelize';
import { sequelize } from '../db/sequelize.js';
export const Blog = sequelize.define("blog", {
title: {
type: DataTypes.STRING,
allowNull: false
},
author: {
type: DataTypes.STRING,
allowNull: false,
}
});
```
3. 实现增删改查操作:
```js
let fn_getById = async (ctx, next) => {
let id = ctx.params.id || 0;
let blog = await Blog.findByPk(id);
ctx.render('blogsAddOrEdit.html', { blog });
}
```
- 使用 `Blog.findByPk(id)` 查询指定 ID 的博客。
- 将结果渲染到 `blogsAddOrEdit.html` 模板。
```js
let fn_add = async (ctx, next) => {
let obj = ctx.request.body;
await Blog.create(obj);
}
```
- 使用 `Blog.create(obj)` 创建新的博客记录。
```js
let fn_update = async (ctx, next) => {
let id = ctx.params.id || 0;
let obj = ctx.request.body;
await Blog.update(obj, { where: { id: id } });
ctx.body = '修改成功';
}
```
- 使用 `Blog.update(obj, { where: { id } })` 更新指定 ID 的博客。
```js
let fn_del = async (ctx, next) => {
let id = ctx.params.id || 0;
await Blog.destroy({ where: { id: id } });
ctx.body = '删除成功';
}
```
- 使用 `Blog.destroy({ where: { id } })` 删除指定 ID 的博客。