• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

012-GoORM框架之Gorm测试

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

1:参考:https://github.com/jinzhu/gorm

2:数据库脚本(pg)

--
create table posts(
    id            serial primary key,
    content        text,
    author        varchar(100),
    create_time    timestamptz
);

create table comments(
    id            serial primary key,
    content        text,
    author        varchar(100),
    post_id        int references posts(id),
    create_time    timestamptz
);

3:posts.go

package posts

import(
	"fmt"
	"github.com/jinzhu/gorm"
	_"github.com/lib/pq"
	"time"
)


type Comment struct{
	ID			int 		
	Content		string		`sql:"not null"`
	Author		string		`sql:"not null"`
	PostId		int 		`sql:"post_id"`
	CreateTime	time.Time	`sql:"create_time"`
}

type Post struct{
	ID			int 		
	Content		string		`sql:"not null"`
	Author		string		`sql:"not null"`
	CreateTime	time.Time	`sql:"create_time"`
	Comments	[]Comment
}


const(
    host = "192.168.72.128"
    port = 5432
    user = "test"
    password = "test"
    dbname = "testdb"
)

var Db *gorm.DB

func init(){
	var err error
	
	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",host, port, user, password, dbname)

	Db, err = gorm.Open("postgres", psqlInfo)
	if err != nil{
		panic(err)
	}

	Db.AutoMigrate(&Post{}, &Comment{})
}

func (post *Post) CreatePost() error{
	return Db.Create(post).Error
}

func (comment *Comment) CreateComment(post *Post) error{
	return Db.Model(post).Association("Comments").Append(comment).Error
}

func (post *Post) GetComments() (comments []Comment, err error){
	Db.Where("author=$1", "王五").First(post)
	err = Db.Model(&post).Related(&comments).Error
	return
}

 4:main.go

package main

import(
	"fmt"
	"time"
	"Chapter02/posts"
)

func main(){
	post := posts.Post{
		Content:"Hello go!",
		Author:"王五",
		CreateTime:	time.Now(),
	}

	fmt.Println(post)

	err := post.CreatePost()
	if err!=nil{
		panic(err)
	}
	fmt.Println(post)

	comment := posts.Comment{
		Content:"不错哟",
		Author:"小二",
		CreateTime:	time.Now(),
	}
	err = comment.CreateComment(&post)
	if err != nil{
		panic(err)
	}

	post = posts.Post{}
	comments, err := post.GetComments()
	if err != nil{
		panic(err)
	}
	for _,p :=  range comments{
		fmt.Printf("%s-%s\n", p.Author,p.Content)
	}
}

  

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go语言使用grpc发布时间:2022-07-10
下一篇:
【原创】go语言之打印目录发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap