dtcyv3985 2018-01-19 13:19
浏览 35
已采纳

在Postgresql数据库中存储递归go结构

I have two structs (Person and Tenant) that reference each other recursively.

I have no experience with 'SQL' and Im trying to use the https://github.com/jmoiron/sqlx library to store these structs in a way that they keep referencing each other, so that I can retrieve them again as structs.

I don't know which type should the tables be created with or how I am supposed to insert the objects to get it work.

Also If there is any other go library that can handle this case easily i'm open to any suggestions.

Thanks in advance.

type Tenant struct {
    Id     int      `db:"id"`
    Name   string   `db:"name"`
    Person []Person `db:"person"`
}
type Person struct {
    Id       int       `db:"id"`
    Username string    `db:"username"`
    Tenants  *[]Tenant `db:"tenants"`
}
func main() {

    var schema = `
                       CREATE TABLE IF NOT EXISTS person (
                           id int,
                           username text
                           tenants []text //-> type????
                       );

                       CREATE TABLE IF NOT EXISTS tenant (
                           id int,
                           name text,
                           person []text //-> type????
                       )`

    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=%s",
        host, port, user, password, dbname, sslmode)

    db, err := sqlx.Open("postgres", psqlInfo)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected!")

    db.MustExec(schema)

    var tenant1 Tenant
    var person1 Person
    tenant1 = Tenant{1, "newtenant", []Person{person1}}
    person1 = Person{1, "newuser", &[]Tenant{tenant1}}

    tx := db.MustBegin()

    tx.NamedExec("INSERT INTO tenant (id,name,person) VALUES (:id,:name, :person)", &tenant1)
    tx.Commit()
    out := []Tenant{}
    db.Select(&out, "SELECT * FROM tenant ORDER BY name ASC")

    fmt.Println(out)
}
  • 写回答

1条回答 默认 最新

  • dongwei3151 2018-01-19 13:49
    关注

    NOTE: This is not a real answer, just a longer comment on the SQL part of the question. Unfortunately I have no experience with sqlx so I cannot help you with that.


    What you have there seems to be a many-to-many relationship. A Person can belong to multiple Tenants and a Tenant can have multiple Persons.

    In SQL this is usually handled by, what's sometimes called, a linking or junction table.

    -- postgresql flavor of SQL
    
    CREATE TABLE IF NOT EXISTS person (
        id serial PRIMARY KEY,
        username text NOT NULL
    );
    
    CREATE TABLE IF NOT EXISTS tenant (
        id serial PRIMARY KEY,
        name text NOT NULL
    );
    
    -- the linking table
    CREATE TABLE IF NOT EXISTS person_tenant (
        person_id integer NOT NULL REFERENCES person (id),
        tenant_id integer NOT NULL REFERENCES tenant (id),
        PRIMARY KEY(person_id, tenant_id)
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 php5.3内存泄露
    • ¥15 DigSilent如何复制复合模型到自己案例?
    • ¥15 求日版华为b610s-77a 官方公版固件,有偿
    • ¥15 关于#java#的问题,请各位专家解答!(相关搜索:java程序)
    • ¥15 linux tsi721的驱动编译后 insmod 提示 报错
    • ¥20 multisim测数据
    • ¥15 求无向连通网的所有不同构的最小生成树
    • ¥15 模拟器的framebuffer问题
    • ¥15 opencv检测轮廓问题
    • ¥15 单点式登录SSO怎么爬虫获取动态SSO_AUTH_ACCESS_Token