()
| 661 | } |
| 662 | |
| 663 | func ExampleDB_Model_hasMany() { |
| 664 | type Profile struct { |
| 665 | Id int |
| 666 | Lang string |
| 667 | Active bool |
| 668 | UserId int |
| 669 | } |
| 670 | |
| 671 | // User has many profiles. |
| 672 | type User struct { |
| 673 | Id int |
| 674 | Name string |
| 675 | Profiles []*Profile `pg:"rel:has-many"` |
| 676 | } |
| 677 | |
| 678 | db := connect() |
| 679 | defer db.Close() |
| 680 | |
| 681 | qs := []string{ |
| 682 | "CREATE TEMP TABLE users (id int, name text)", |
| 683 | "CREATE TEMP TABLE profiles (id int, lang text, active bool, user_id int)", |
| 684 | "INSERT INTO users VALUES (1, 'user 1')", |
| 685 | "INSERT INTO profiles VALUES (1, 'en', TRUE, 1), (2, 'ru', TRUE, 1), (3, 'md', FALSE, 1)", |
| 686 | } |
| 687 | for _, q := range qs { |
| 688 | _, err := db.Exec(q) |
| 689 | if err != nil { |
| 690 | panic(err) |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | // Select user and all his active profiles with following queries: |
| 695 | // |
| 696 | // SELECT "user".* FROM "users" AS "user" ORDER BY "user"."id" LIMIT 1 |
| 697 | // |
| 698 | // SELECT "profile".* FROM "profiles" AS "profile" |
| 699 | // WHERE (active IS TRUE) AND (("profile"."user_id") IN ((1))) |
| 700 | |
| 701 | var user User |
| 702 | err := db.Model(&user). |
| 703 | Column("user.*"). |
| 704 | Relation("Profiles", func(q *pg.Query) (*pg.Query, error) { |
| 705 | return q.Where("active IS TRUE"), nil |
| 706 | }). |
| 707 | First() |
| 708 | if err != nil { |
| 709 | panic(err) |
| 710 | } |
| 711 | fmt.Println(user.Id, user.Name, user.Profiles[0], user.Profiles[1]) |
| 712 | // Output: 1 user 1 &{1 en true 1} &{2 ru true 1} |
| 713 | } |
| 714 | |
| 715 | func ExampleDB_Model_hasManySelf() { |
| 716 | type Item struct { |
nothing calls this directly
no test coverage detected
searching dependent graphs…