012-Go ORM框架之Gorm测试

Posted YSHY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了012-Go ORM框架之Gorm测试相关的知识,希望对你有一定的参考价值。

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)
	}
}

  

 

以上是关于012-Go ORM框架之Gorm测试的主要内容,如果未能解决你的问题,请参考以下文章

Golang之ORM框架Gorm快速开始

Golang之ORM框架Gorm快速开始

golang orm 框架之 gorm

golang orm 框架之 gorm

Go开源世界主流成熟ORM框架gorm实践分享

初学 go 入门-案例-教程-记录(13)orm 框架 Gorm 简单案例 - 连接sqlserver,并查询数据