| 604 | } |
| 605 | |
| 606 | func ExampleDB_Model_belongsTo() { |
| 607 | // Profile belongs to User. |
| 608 | type Profile struct { |
| 609 | Id int |
| 610 | Lang string |
| 611 | UserId int |
| 612 | } |
| 613 | |
| 614 | type User struct { |
| 615 | Id int |
| 616 | Name string |
| 617 | Profile *Profile `pg:"rel:belongs-to"` |
| 618 | } |
| 619 | |
| 620 | db := connect() |
| 621 | defer db.Close() |
| 622 | |
| 623 | qs := []string{ |
| 624 | "CREATE TEMP TABLE users (id int, name text)", |
| 625 | "CREATE TEMP TABLE profiles (id int, lang text, user_id int)", |
| 626 | "INSERT INTO users VALUES (1, 'user 1'), (2, 'user 2')", |
| 627 | "INSERT INTO profiles VALUES (1, 'en', 1), (2, 'ru', 2)", |
| 628 | } |
| 629 | for _, q := range qs { |
| 630 | _, err := db.Exec(q) |
| 631 | if err != nil { |
| 632 | panic(err) |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | // Select users joining their profiles with following query: |
| 637 | // |
| 638 | // SELECT |
| 639 | // "user".*, |
| 640 | // "profile"."id" AS "profile__id", |
| 641 | // "profile"."lang" AS "profile__lang", |
| 642 | // "profile"."user_id" AS "profile__user_id" |
| 643 | // FROM "users" AS "user" |
| 644 | // LEFT JOIN "profiles" AS "profile" ON "profile"."user_id" = "user"."id" |
| 645 | |
| 646 | var users []User |
| 647 | err := db.Model(&users). |
| 648 | Column("user.*"). |
| 649 | Relation("Profile"). |
| 650 | Select() |
| 651 | if err != nil { |
| 652 | panic(err) |
| 653 | } |
| 654 | |
| 655 | fmt.Println(len(users), "results") |
| 656 | fmt.Println(users[0].Id, users[0].Name, users[0].Profile) |
| 657 | fmt.Println(users[1].Id, users[1].Name, users[1].Profile) |
| 658 | // Output: 2 results |
| 659 | // 1 user 1 &{1 en 1} |
| 660 | // 2 user 2 &{2 ru 2} |
| 661 | } |
| 662 | |
| 663 | func ExampleDB_Model_hasMany() { |