Skip to content
导航栏

创建数据模型

一个数据模型对应数据库中的一张数据表, 通过 Model DSL 文件描述数据表结构, 使用 relations 描述数据表之间关联关系, 使用 yao migrate 命令创建/更新数据表结构设计。

约定

  1. 示例中约定应用根目录为 /data/app, 实际编写时需替换为应用根目录。
  2. 使用 <> 标识自行替换的内容。 例如: icon-<图标名称>, 实际编写时应替换为: icon-foo, icon-bar ...

编写数据模型

添加模型 DSL 文件

models 目录下, 创建一个 Model DSL 文件, 设计一张 product 数据表。

/data/app/models/product.mod.json

json
{
  "name": "产品",
  "table": { "name": "product", "comment": "产品表" },
  "columns": [
    { "label": "ID", "name": "id", "type": "ID", "comment": "ID" },
    { "label": "日期", "name": "day", "type": "datetime", "index": true },
    {
      "label": "名称",
      "name": "name",
      "type": "string",
      "length": 128,
      "index": true
    },
    {
      "label": "上架状态",
      "name": "online",
      "type": "boolean",
      "default": false,
      "comment": "上架状态 true 上架 false 下架",
      "index": true
    },
    {
      "label": "状态",
      "name": "status",
      "type": "enum",
      "default": "enabled",
      "option": ["enabled", "disabled"],
      "comment": "状态:enabled打开,disabled关闭",
      "index": true
    },
    { "label": "用户ID", "name": "user_id", "type": "integer", "index": true },
    { "label": "总金额", "name": "amount", "type": "decimal", "index": true },
    { "label": "备注", "name": "remark", "type": "text", "nullable": true }
  ],
  "values": [],
  "relations": {
    "users": {
      "type": "hasOne",
      "model": "xiang.user",
      "key": "id",
      "foreign": "user_id",
      "query": {}
    }
  },
  "option": { "timestamps": true, "soft_deletes": true }
}

提示:option.timestamps 为 true, 自动创建 created_atupdated_at 字段, 用于保存数据记录的创建时间和更新时间。 option.soft_deletes 为 true, 自动创建 deleted_at 字段, 用于标记删除记录。

更新数据表结构

进入应用目录,运行 yao migrate 命令创建数据表

bash
cd /data/app
yao migrate -n product

注意:migrate 命令可能修改数据库中同名数据表结构,请注意数据备份。

数据查询

新增一条数据

bash
yao run models.product.Create '::{"name":"悉达多", "day":"2022-01-01 08:00:00", "status":"enabled", "user_id":1,"amount":1000,"remark":"Book ....."}'

更新一条数据

bash
yao run models.product.Update 1 '::{"remark":"一本工具书"}'

保存一条数据,指定主键则更新,不指定创建创建。

bash
yao run models.product.Save '::{"name":"资治通鉴", "day":"2022-01-01 08:00:00", "status":"enabled", "user_id":1,"amount":1000,"remark":"Book ....."}'
bash
yao run models.product.Save '::{"id":1,"remark":"黑塞的小说"}'

列表查询

bash
yao run models.product.Get '::{}'

列表查询(分页)

bash
yao run models.product.Paginate '::{}' 1 2

按主键查询数据

bash
yao run models.product.find 1 '::{}'

删除一条数据

bash
yao run models.product.Delete 1 '::{}'