ORM
创建第一个 model
假设您已经set up了 Lucid,那么运行以下命令来创建您的第一个数据模型。
js1node ace make:model User -m
上面的命令会自动创建两个文件
js1CREATE: app/Models/User.ts 2CREATE: database/migrations/1678525151584_users.ts
Models 目录下是定义给 ORM 用的 model 对象,需要自己补充字段和类型,这样会有自动提示。
js1import { DateTime } from "luxon"; 2import { BaseModel, column } from "@ioc:Adonis/Lucid/Orm"; 3 4export default class User extends BaseModel { 5 @column({ isPrimary: true }) 6 public id: number; 7 8 @column() 9 public user: string; 10 11 @column() 12 public password: string; 13 14 @column.dateTime({ autoCreate: true }) 15 public createdAt: DateTime; 16 17 @column.dateTime({ autoCreate: true, autoUpdate: true }) 18 public updatedAt: DateTime; 19}
database/migrations目录下用于 migration,在这里定义的字段会在创建表时 migration 到数据库中。
js1import BaseSchema from "@ioc:Adonis/Lucid/Schema"; 2 3export default class extends BaseSchema { 4 protected tableName = "users"; 5 6 public async up() { 7 this.schema.createTable(this.tableName, (table) => { 8 table.increments("id"); 9 table.string("password"); 10 table.string("user"); 11 /** 12 * Uses timestamptz for PostgreSQL and DATETIME2 for MSSQL 13 */ 14 table.timestamp("created_at", { useTz: true }); 15 table.timestamp("updated_at", { useTz: true }); 16 }); 17 } 18 19 public async down() { 20 this.schema.dropTable(this.tableName); 21 } 22}
执行命令以创建一张表
js1node ace migration:run