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

Function ExampleDB_Model_hasOne

example_model_test.go:550–604  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

548}
549
550func ExampleDB_Model_hasOne() {
551 type Profile struct {
552 Id int
553 Lang string
554 }
555
556 // User has one profile.
557 type User struct {
558 Id int
559 Name string
560 ProfileId int
561 Profile *Profile `pg:"rel:has-one"`
562 }
563
564 db := connect()
565 defer db.Close()
566
567 qs := []string{
568 "CREATE TEMP TABLE users (id int, name text, profile_id int)",
569 "CREATE TEMP TABLE profiles (id int, lang text)",
570 "INSERT INTO users VALUES (1, 'user 1', 1), (2, 'user 2', 2)",
571 "INSERT INTO profiles VALUES (1, 'en'), (2, 'ru')",
572 }
573 for _, q := range qs {
574 _, err := db.Exec(q)
575 if err != nil {
576 panic(err)
577 }
578 }
579
580 // Select users joining their profiles with following query:
581 //
582 // SELECT
583 // "user".*,
584 // "profile"."id" AS "profile__id",
585 // "profile"."lang" AS "profile__lang"
586 // FROM "users" AS "user"
587 // LEFT JOIN "profiles" AS "profile" ON "profile"."id" = "user"."profile_id"
588
589 var users []User
590 err := db.Model(&users).
591 Column("user.*").
592 Relation("Profile").
593 Select()
594 if err != nil {
595 panic(err)
596 }
597
598 fmt.Println(len(users), "results")
599 fmt.Println(users[0].Id, users[0].Name, users[0].Profile)
600 fmt.Println(users[1].Id, users[1].Name, users[1].Profile)
601 // Output: 2 results
602 // 1 user 1 &{1 en}
603 // 2 user 2 &{2 ru}
604}
605
606func ExampleDB_Model_belongsTo() {
607 // Profile belongs to User.

Callers

nothing calls this directly

Calls 7

connectFunction · 0.85
ColumnMethod · 0.80
CloseMethod · 0.65
ExecMethod · 0.65
RelationMethod · 0.65
ModelMethod · 0.65
SelectMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…