阅读ent文档
This commit is contained in:
77
Golang/ent.md
Normal file
77
Golang/ent.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# 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
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user