doulai2025 2017-08-01 18:01
浏览 109

gorm + go + pg:查询相关

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.

  • 写回答

1条回答 默认 最新

  • drbuowqe02101 2017-08-09 14:44
    关注

    Remove the pointer and it will work

    Reference: http://jinzhu.me/gorm/associations.html

    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大