MCPcopy Create free account
hub / github.com/go-pg/pg / ExampleDB_Model_hasManySelf

Function ExampleDB_Model_hasManySelf

example_model_test.go:715–751  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

713}
714
715func ExampleDB_Model_hasManySelf() {
716 type Item struct {
717 Id int
718 Items []Item `pg:"rel:has-many,join_fk:parent_id"`
719 ParentId int
720 }
721
722 db := connect()
723 defer db.Close()
724
725 qs := []string{
726 "CREATE TEMP TABLE items (id int, parent_id int)",
727 "INSERT INTO items VALUES (1, NULL), (2, 1), (3, 1)",
728 }
729 for _, q := range qs {
730 _, err := db.Exec(q)
731 if err != nil {
732 panic(err)
733 }
734 }
735
736 // Select item and all subitems with following queries:
737 //
738 // SELECT "item".* FROM "items" AS "item" ORDER BY "item"."id" LIMIT 1
739 //
740 // SELECT "item".* FROM "items" AS "item" WHERE (("item"."parent_id") IN ((1)))
741
742 var item Item
743 err := db.Model(&item).Column("item.*").Relation("Items").First()
744 if err != nil {
745 panic(err)
746 }
747 fmt.Println("Item", item.Id)
748 fmt.Println("Subitems", item.Items[0].Id, item.Items[1].Id)
749 // Output: Item 1
750 // Subitems 2 3
751}
752
753func ExampleDB_Model_update() {
754 db := modelDB()

Callers

nothing calls this directly

Calls 7

connectFunction · 0.85
FirstMethod · 0.80
ColumnMethod · 0.80
CloseMethod · 0.65
ExecMethod · 0.65
RelationMethod · 0.65
ModelMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…