Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vmihailenco/065dd023bee888f9505edf0099691f00 to your computer and use it in GitHub Desktop.
Save vmihailenco/065dd023bee888f9505edf0099691f00 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
// "log"
// "time"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
type Blog struct {
TableName struct{} `protobuf:"bytes,1,opt,name=tableName" json:"tableName,omitempty" sql:"blog"`
BlogId int64 `protobuf:"varint,2,opt,name=blogId,proto3" json:"blogId,omitempty" sql:"blog_id,pk"`
Url string `protobuf:"bytes,3,opt,name=url,proto3" json:"url,omitempty" sql:"url"`
Places []*Place `protobuf:"bytes,5,rep,name=places" json:"places,omitempty" pg:",many2many:blog_to_places,fk:blog_id,joinFK:place_id"`
}
type Place struct {
TableName struct{} `protobuf:"bytes,1,opt,name=tableName" json:"tableName,omitempty" sql:"place"`
PlaceId int64 `protobuf:"varint,2,opt,name=placeId,proto3" json:"placeId,omitempty" sql:"place_id,pk"`
Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty" sql:"name"`
}
type BlogToPlace struct {
BlogId int
PlaceId int
}
func createManyToManyTables(db *pg.DB) error {
models := []interface{}{
(*Blog)(nil),
(*Place)(nil),
(*BlogToPlace)(nil),
}
for _, model := range models {
err := db.CreateTable(model, &orm.CreateTableOptions{
Temp: true,
})
if err != nil {
return err
}
}
return nil
}
func Connect() *pg.DB {
db := pg.Connect(&pg.Options{
User: "postgres",
})
db.OnQueryProcessed(func(event *pg.QueryProcessedEvent) {
query, err := event.FormattedQuery()
if err != nil {
panic(err)
}
fmt.Println(query)
})
return db
}
func main() {
db := Connect()
defer db.Close()
if err := createManyToManyTables(db); err != nil {
panic(err)
}
values := []interface{}{
&Blog{BlogId: 1, Url: "test1"},
&Blog{BlogId: 2, Url: "test2"},
&Place{PlaceId: 1, Name: "test place"},
&BlogToPlace{BlogId: 1, PlaceId: 1},
&BlogToPlace{BlogId: 1, PlaceId: 1},
}
for _, v := range values {
err := db.Insert(v)
if err != nil {
panic(err)
}
}
// Select order and all items with following queries:
//
// SELECT "order"."id" FROM "orders" AS "order" ORDER BY "order"."id" LIMIT 1
//
// SELECT order_to_items.*, "item"."id" FROM "items" AS "item"
// JOIN order_to_items AS order_to_items ON (order_to_items."order_id") IN (1)
// WHERE ("item"."id" = order_to_items."item_id")
blog := new(Blog)
err := db.Model(blog).Relation("Places").First()
// err := db.Model(place).Select
if err != nil {
panic(err)
}
fmt.Println("Blog", blog.BlogId, "Places", blog.Places[0].PlaceId)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment