W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
Ent 是 Facebook 開(kāi)源的一個(gè)簡(jiǎn)單易用的 Database 實(shí)體框架。
它使構(gòu)建和維護(hù)具有大型數(shù)據(jù)模型的應(yīng)用程序變得容易,并堅(jiān)持以下原則:
go install entgo.io/ent/cmd/ent
ent init User
將會(huì)在 project/ent/schema/ 目錄下為用戶生成模式:
// <project>/ent/schema/user.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
?添加 ?name、age
? 兩個(gè)數(shù)據(jù)庫(kù)字段:
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.Int("age").
Positive(),
field.String("name").
Default("unknown"),
}
}
從項(xiàng)目的ent目錄運(yùn)行g(shù)o generate,如下所示:
go generate ./ent
首先,創(chuàng)建一個(gè)新的ent.Client。對(duì)于本例,我們將使用SQLite3。
package main
import (
"context"
"log"
"<project>/ent"
_ "github.com/mattn/go-sqlite3"
)
func main() {
client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
if err != nil {
log.Fatalf("failed opening connection to sqlite: %v", err)
}
defer client.Close()
// Run the auto migration tool.
if err := client.Schema.Create(context.Background()); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
}
然后進(jìn)行創(chuàng)建一個(gè) ?User
?將會(huì)寫入到數(shù)據(jù)庫(kù)中:
func CreateUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
u, err := client.User.
Create().
SetAge(30).
SetName("a8m").
Save(ctx)
if err != nil {
return nil, fmt.Errorf("failed creating user: %v", err)
}
log.Println("user was created: ", u)
return u, nil
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: