Gorm属于不返回关联关系。

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

Gorm belongs to does not return relations

问题

我有以下这些模型:

type Message struct {
    gorm.Model
    UserID  uint   `json:"userId"`
    User    userModels.User
    Content string `json:"content"`
}

type Receiver struct {
    gorm.Model
    UserID    uint   `json:"userId"`
    User      userModels.User
    FirstName string `json:"firstName"`
    LastName  string `json:"lastName"`
    Email     string `json:"email"`
    Address   string `json:"address"`
    Phone     string `json:"phone"`
}

type Delivery struct {
    gorm.Model
    Message      Message   `json:"message"`
    MessageID    uint      `json:"messageId"`
    Receiver     Receiver  `json:"receiver"`
    ReceiverID   uint      `json:"receiverId"`
    DeliveryDate time.Time `json:"deliveryDate"`
    Sent         bool      `json:"sent"`
}

我在数据库中插入了一些具有特定MessageID和ReceiverID的Delivery。当我查询该特定Delivery时,我期望得到相应的Message和具有ReceiverID的Receiver。

但是我得到的是一个既没有Message对象也没有Receiver对象的Delivery。

以下是我得到的结果:

{
    "ID": 2,
    "CreatedAt": "2021-08-26T04:44:33.366628+04:30",
    "UpdatedAt": "2021-08-26T04:44:33.366628+04:30",
    "DeletedAt": null,
    "message": {
        "ID": 0,
        "CreatedAt": "0001-01-01T00:00:00Z",
        "UpdatedAt": "0001-01-01T00:00:00Z",
        "DeletedAt": null,
        "userId": 0,
        "User": {
            "ID": 0,
            "CreatedAt": "0001-01-01T00:00:00Z",
            "UpdatedAt": "0001-01-01T00:00:00Z",
            "DeletedAt": null,
            "firstName": "",
            "lastName": "",
            "email": "",
            "password": "",
            "country": "",
            "dateOfBirth": "0001-01-01T00:00:00Z",
            "rank": "",
            "gender": "",
            "plan": ""
        },
        "content": ""
    },
    "messageId": 2,
    "Receiver": {
        "ID": 0,
        "CreatedAt": "0001-01-01T00:00:00Z",
        "UpdatedAt": "0001-01-01T00:00:00Z",
        "DeletedAt": null,
        "userId": 0,
        "User": {
            "ID": 0,
            "CreatedAt": "0001-01-01T00:00:00Z",
            "UpdatedAt": "0001-01-01T00:00:00Z",
            "DeletedAt": null,
            "firstName": "",
            "lastName": "",
            "email": "",
            "password": "",
            "country": "",
            "dateOfBirth": "0001-01-01T00:00:00Z",
            "rank": "",
            "gender": "",
            "plan": ""
        },
        "firstName": "",
        "lastName": "",
        "email": "",
        "address": "",
        "phone": ""
    },
    "receiverId": 1,
    "deliveryDate": "2021-08-25T05:18:27.950457+04:30",
    "sent": false
}

而我期望它返回我指定的messageId的Message和具有ReceiverID的Receiver。

英文:

I have these models

    type Message struct {
gorm.Model
UserID  uint `json:"userId"`
User    userModels.User
Content string `json:"content"`
}
type Receiver struct {
gorm.Model
UserID    uint `json:"userId"`
User      userModels.User
FirstName string `json:"firstName"`
LastName  string `json:"lastName"`
Email     string `json:"email"`
Address   string `json:"address"`
Phone     string `json:"phone"`
}
type Delivery struct {
gorm.Model
Message      Message   `json:"message"`
MessageID    uint      `json:"messageId"`
Receiver     Receiver  `json:"Receiver"`
ReceiverID   uint      `json:"receiverId"`
DeliveryDate time.Time `json:"deliveryDate"`
Sent         bool      `json:"sent"`
}

I insert some Delivery in the database with certain MessageID and ReceiverID. When I query that certain Delivery I expect to get the regarding message with the id of MessageID, and a Receiver of id ReceiverID.
But what I get is a Delivery with both empty Message and Receiver objects.

this is what I get:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

 {
&quot;ID&quot;: 2,
&quot;CreatedAt&quot;: &quot;2021-08-26T04:44:33.366628+04:30&quot;,
&quot;UpdatedAt&quot;: &quot;2021-08-26T04:44:33.366628+04:30&quot;,
&quot;DeletedAt&quot;: null,
&quot;message&quot;: {
&quot;ID&quot;: 0,
&quot;CreatedAt&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;UpdatedAt&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;DeletedAt&quot;: null,
&quot;userId&quot;: 0,
&quot;User&quot;: {
&quot;ID&quot;: 0,
&quot;CreatedAt&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;UpdatedAt&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;DeletedAt&quot;: null,
&quot;firstName&quot;: &quot;&quot;,
&quot;lastName&quot;: &quot;&quot;,
&quot;email&quot;: &quot;&quot;,
&quot;password&quot;: &quot;&quot;,
&quot;country&quot;: &quot;&quot;,
&quot;dateOfBirth&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;rank&quot;: &quot;&quot;,
&quot;gender&quot;: &quot;&quot;,
&quot;plan&quot;: &quot;&quot;
},
&quot;content&quot;: &quot;&quot;
},
&quot;messageId&quot;: 2,
&quot;Receiver&quot;: {
&quot;ID&quot;: 0,
&quot;CreatedAt&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;UpdatedAt&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;DeletedAt&quot;: null,
&quot;userId&quot;: 0,
&quot;User&quot;: {
&quot;ID&quot;: 0,
&quot;CreatedAt&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;UpdatedAt&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;DeletedAt&quot;: null,
&quot;firstName&quot;: &quot;&quot;,
&quot;lastName&quot;: &quot;&quot;,
&quot;email&quot;: &quot;&quot;,
&quot;password&quot;: &quot;&quot;,
&quot;country&quot;: &quot;&quot;,
&quot;dateOfBirth&quot;: &quot;0001-01-01T00:00:00Z&quot;,
&quot;rank&quot;: &quot;&quot;,
&quot;gender&quot;: &quot;&quot;,
&quot;plan&quot;: &quot;&quot;
},
&quot;firstName&quot;: &quot;&quot;,
&quot;lastName&quot;: &quot;&quot;,
&quot;email&quot;: &quot;&quot;,
&quot;address&quot;: &quot;&quot;,
&quot;phone&quot;: &quot;&quot;
},
&quot;receiverId&quot;: 1,
&quot;deliveryDate&quot;: &quot;2021-08-25T05:18:27.950457+04:30&quot;,
&quot;sent&quot;: false
}

<!-- end snippet -->

While I expect it to return the message with the messageId I specified and also the receiver

答案1

得分: 2

当我查询特定的交付时,你好。如果你使用Preload,你将获得接收者和消息的详细信息。如果你不使用Preload,你将得到一个包含空消息和接收者对象的交付对象。如果你只需要消息ID和接收者ID,你应该将Message Message更改为Message *Message,将Receiver Receiver更改为Receiver *Receiver。如果你使用Preload,结果与上述相同。如果你不使用Preload,接收者和消息将为nil。以下是所有的测试代码和调试信息:

type User3 struct {
	gorm.Model
	Name string
}

type Message struct {
	gorm.Model
	UserID  uint   `json:"userId"`
	User    *User3
	Content string `json:"content"`
}

type Receiver struct {
	gorm.Model
	UserID    uint   `json:"userId"`
	User      *User3
	FirstName string `json:"firstName"`
	LastName  string `json:"lastName"`
	Email     string `json:"email"`
	Address   string `json:"address"`
	Phone     string `json:"phone"`
}

type Delivery struct {
	gorm.Model
	Message      *Message   `json:"message"`
	MessageID    uint       `json:"messageId"`
	Receiver     *Receiver  `json:"receiver"`
	ReceiverID   uint       `json:"receiverId"`
	DeliveryDate time.Time  `json:"deliveryDate"`
	Sent         bool       `json:"sent"`
}

func main() {
	db := config.CreateMysql()
	db.AutoMigrate(Delivery{})

	d := Delivery{
		Message: &Message{
			User:    &User3{Name: "a"},
			Content: "hello b~",
		},
		Receiver: &Receiver{
			User: &User3{Name: "b"},
		},
		DeliveryDate: time.Now(),
		Sent:         false,
	}
	db.Create(&d)

	d2 := Delivery{}
	db.First(&d2)
	fmt.Printf("%v\n", d2)

	d3 := Delivery{}
	db.Preload("Message").Preload("Receiver").First(&d3)
	fmt.Printf("%v\n", d3)
}

上述用户为nil,如果你想预加载嵌套关联,请使用以下方式:.Preload("Message.User")。详细信息请参考:https://gorm.io/docs/preload.html

英文:

When I query that certain Delivery

how do you do?

if you uses Preload
db.Preload(&quot;Message&quot;).Preload(&quot;Receiver&quot;).First(&amp;d3)

you will get the deltial of Receiver and message like

if you don't uses Preload
what you get is a Delivery with both empty Message and Receiver objects.

if you only need messageId and receiverID
you should change the Message Message to Message *Message and Receiver Receiver to Receiver *Receiver

if you uses Preload -> same to above

if you don't uses Preload -> Receiver and Message will be nil

follow is all test code and debug info:

type User3 struct {
gorm.Model
Name      string
}
type Message struct {
gorm.Model
UserID  uint `json:&quot;userId&quot;`
User    *User3
Content string `json:&quot;content&quot;`
}
type Receiver struct {
gorm.Model
UserID    uint `json:&quot;userId&quot;`
User      *User3
FirstName string `json:&quot;firstName&quot;`
LastName  string `json:&quot;lastName&quot;`
Email     string `json:&quot;email&quot;`
Address   string `json:&quot;address&quot;`
Phone     string `json:&quot;phone&quot;`
}
type Delivery struct {
gorm.Model
Message      *Message   `json:&quot;message&quot;`
MessageID    uint      `json:&quot;messageId&quot;`
Receiver     *Receiver  `json:&quot;Receiver&quot;`
ReceiverID   uint      `json:&quot;receiverId&quot;`
DeliveryDate time.Time `json:&quot;deliveryDate&quot;`
Sent         bool      `json:&quot;sent&quot;`
}
func main() {
db := config.CreateMysql()
db.AutoMigrate(Delivery{})
d := Delivery{Message: &amp;Message{User: &amp;User3{Name: &quot;a&quot;}, Content: &quot;hello b~&quot;}, Receiver: &amp;Receiver{User: &amp;User3{Name: &quot;b&quot;}}, DeliveryDate: time.Now(), Sent: false}
db.Create(&amp;d)
d2 := Delivery{}
db.First(&amp;d2)
fmt.Printf(&quot;%v\n&quot;, d2)
d3 := Delivery{}
db.Preload(&quot;Message&quot;).Preload(&quot;Receiver&quot;).First(&amp;d3)
fmt.Printf(&quot;%v\n&quot;, d3)
}

Gorm属于不返回关联关系。

ps: above user is nil, if you want preload nested associations, uses follow:
.Preload(&quot;Message.User&quot;)
https://gorm.io/docs/preload.html

huangapple
  • 本文由 发表于 2021年8月26日 08:33:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/68931208.html
匿名

发表评论

匿名网友

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

确定