dsfds4551 2018-05-18 07:19
浏览 234
已采纳

为什么Gorm在CreateTable时会忽略结构?

What version of Go am I using (go version)?

Go version Go 1.9.1 Linux/amd64

Which database and its version am I using?

sqlite3

A complete runnable program to reproduce my issue:

Need to runnable with GORM's docker compose config or please provide your config.

package main

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type A struct {
    ID      int
    Bs              [] *B `gorm:"foreignkey:AID"`
}

type B struct {
    ID      int
    AID     int
    Config          Config `gorm:"type:text"`
}

type Config struct {
    attr1   int
    attr2   string
}


func main() {
    Db, err := gorm.Open("sqlite3", "test.db")
    if err != nil {
        panic(err)
    }
    Db.CreateTable(&A{})
    Db.CreateTable(&B{})
}

However, the schema of test.db is

sqlite> .schema
CREATE TABLE "as" ("id" integer primary key autoincrement );
CREATE TABLE "bs" ("id" integer primary key autoincrement,"a_id" integer );

As we can see, B's config attribute was not created. So Why Gorm is ignoring the Config struct?

  • 写回答

1条回答 默认 最新

  • duanju8308 2018-05-18 08:28
    关注

    You data is not normalized. Config is a struct with multiple fields. You can extract config into a separate table with a foreign key, like you did with B:

    type B struct {
        ID     int
        AID    int
        Config Config `gorm:"foreignkey:BID"`
    }
    

    And then define the foreign key in Config:

    type Config struct {
        BID   int
        attr1 int
        attr2 string
    }
    

    At the end, you create the table:

    Db.CreateTable(&Config{})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器