【问题标题】:GORM JOINs and ResultsGORM JOIN 和结果
【发布时间】:2019-03-28 10:46:51
【问题描述】:

假设我有两个表,它们共享一些列名,例如:

table_1
    - id
    - created_at
    - deleted_at
    - name
    - color

table_2
    - id
    - created_at
    - deleted_at
    - address
    - name

当我在这两个表上运行连接查询时,我会得到这样的结果:

id, created_at, name, color, id, created_at, deleted_at, address, name

我有 2 个类似于我上面描述的模型的结构。现在我想将结果扫描到一个结果结构中:

type Result struct {
   Model1
   Model2
}

然后我使用db.Raw().Scan(&result)。现在的问题: table_2id 永远不会写入表 2 的结构中,只会写入结果结构中的表 1 的结构中。

我的问题是:当存在同名的列时,如何将 JOIN 查询的结果读入结果结构中。

【问题讨论】:

  • 你解决过这个问题吗?

标签: go join go-gorm


【解决方案1】:

我不知道这在 Gorm V1 中是否可行,但在 V2 中,您可以使用带有前缀的 Embedded Structs 来消除两个结果集的歧义,然后您可以适当地命名列以将它们定向到正确的嵌入式模型:

type Model1 struct {
    ID    int `gorm:"primaryKey"`
    Value string
}

type Model2 struct {
    ID    int `gorm:"primaryKey"`
    Value string
    Color string
}

type Result struct {
    Model1 `gorm:"embedded;embeddedPrefix:m1_"`
    Model2 `gorm:"embedded;embeddedPrefix:m2_"`
}

res := Result{}
db.Raw(`
    SELECT
        1 AS m1_id,
        'one' AS m1_value,
        2 AS m2_id,
        'two' AS m2_value,
        'rose' AS m2_color
`).Scan(&res)

fmt.Printf("%+v\n", res)
// {Model1:{ID:1 Value:one} Model2:{ID:2 Value:two Color:rose}}

【讨论】:

    猜你喜欢
    • 2018-04-04
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 2017-09-14
    • 1970-01-01
    • 2016-10-07
    相关资源
    最近更新 更多