插入关系 go-pg PostgreSQL

huangapple go评论87阅读模式
英文:

inserting relationships go-pg PostgreSQL

问题

我有两个结构体来表示ManyToMany关系。User和Note

type User struct {
    ID int
    Name string
    Notes []*Note
}

type Note struct {
    TableName struct{} `sql:"user_notes"`
    ID int
    Text string
}

现在假设我想插入一个新用户,并同时添加一些笔记。

我期望这样插入一个用户及其笔记:

note := Note{
    Text: "alohaa dude",
}

user := User{
    Name:  "peter",
    Notes: []*Note{note},
}

s.DB.Insert(&user)

然而,这只保存了用户,而没有保存用户和笔记。在go-pg中,我需要手动完成这个过程,还是ORM有自动化的方式?

英文:

I've got 2 structs to represent a ManyToMany relationship. User and Note

type User struct {
    ID int
    Name string
    Notes []*Note
}

type Note struct {
    TableName struct{} `sql:"user_notes"`
    ID int
    Text string
}

Now let's say I want to insert a new user and also at the same time add a few notes.

I would expect this to insert a user and its note(s):

note := Note{
	Text: "alohaa dude",
}

user := User{
	Name:  "peter",
	Notes: []Note{no},
}

s.DB.Insert(&user)

However this only saves the user and not the user and the note. In go-pg do I have to do this manually or is there an automated way through the ORM?

答案1

得分: 1

Rodrigo,这里正在讨论同样的问题陈述:https://github.com/go-pg/pg/issues/478

目前,go-pg不支持这个功能,你可以尝试使用数据库准备的方法来插入带有关联的数据。

英文:

Rodrigo, same problem statement is being discussed here: https://github.com/go-pg/pg/issues/478

This functionality is not supported in go-pg at this time and you might want to try a db prepare approach to insert with relationships.

huangapple
  • 本文由 发表于 2017年1月9日 12:58:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/41541267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定