So we have a Person with a Name. A First and Last name. Let's insert the Person with the First and Last name and query for the Person by Name.First again. How?
package main
import (
"fmt"
"log"
"github.com/jinzhu/gorm"
)
var (
pgHost string
pgUser string
pgDatabase string
pgPass string
)
type Person struct {
gorm.Model
Name *Name
NameID uint
}
type Name struct {
gorm.Model
PersonID uint
First string
Last string
}
func main() {
// let's assume they're set
db, e := gorm.Open("postgres", fmt.Sprintf("host=%s user=%s dbname=%s password=%s sslmode=disable", pgHost, pgUser, pgDatabase, pgPass))
if e != nil {
log.Fatal(e)
}
defer db.Close()
db.AutoMigrate(&Person{}, &Name{})
p := &Person{
Name: &Name{First: "First", Last: "Last"},
}
tx := db.Begin()
if c := tx.Create(p); c.Error != nil {
log.Fatal("tx.create", c.Error)
}
tx.Commit()
// let's find it
pq := &Person{Name: &Name{First: "First"}}
pr := new(Person)
if c := db.Where(pq).First(pr); c.Error != nil {
log.Fatal("db.Where", c.Error)
}
}
Error Message
converting Exec argument $1 type: unsupported type Name, a struct
Feel free to suggest alternatives, change structs, etc.
No, adding NameFirst
and NameLast
fields isn't acceptable. The 2 structs should remain intact.