Files
rikako-note/Golang/ent.md
2025-02-18 00:50:33 +08:00

78 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ent
## Introduction
ent是一个简单、功能强大的entity framework。下面将会是一个ent的使用示例。
### init project
```bash
go mod init entdemo
```
### 创建schema
在entdemo目录下运行
```bash
go run -mod=mod entgo.io/ent/cmd/ent new User
```
上述命令会为`User`创建schema创建位置位于`entdemo/ent/schema`目录下,`entdemo/ent/schema/user.go`文件内容如下:
```go
package schema
import "entgo.io/ent"
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return nil
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return nil
}
```
### 向User实体中添加字段
可以向User中添加两个字段修改`Field`内容为如下:
```go
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.Int("age").
Positive(),
field.String("name").
Default("unknown"),
}
}
```
### go generate
之后,可以调用`go generate`:
```bash
go generate ./ent
```
产生内容如下:
```
ent
├── client.go
├── config.go
├── context.go
├── ent.go
├── generate.go
├── mutation.go
... truncated
├── schema
│ └── user.go
├── tx.go
├── user
│ ├── user.go
│ └── where.go
├── user.go
├── user_create.go
├── user_delete.go
├── user_query.go
└── user_update.go
```