| 548 | } |
| 549 | |
| 550 | func 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 | |
| 606 | func ExampleDB_Model_belongsTo() { |
| 607 | // Profile belongs to User. |