首页 > 其他 > 详细

012-Go ORM框架之Gorm测试

时间:2018-06-06 23:05:08      阅读:202      评论:0      收藏:0      [点我收藏+]

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测试

原文:https://www.cnblogs.com/yshyee/p/9147675.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!