Skip to content

fix: duplicated preload#6948

Merged
jinzhu merged 1 commit intogo-gorm:masterfrom
bentoml:fix/duplicated-preload-2
Apr 15, 2024
Merged

fix: duplicated preload#6948
jinzhu merged 1 commit intogo-gorm:masterfrom
bentoml:fix/duplicated-preload-2

Conversation

@yetone
Copy link
Copy Markdown
Contributor

@yetone yetone commented Apr 8, 2024

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

When using an anonymous mixin struct, preload will request the same sql twice. This behavior contradicts the statement in the document:

Screenshot 2024-04-09 at 03 08 43

The behavior was as expected before this PR was merged: #6137

This PR aims to fix this issue.

User Case Description

package main

import (
	"testing"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type User struct {
	gorm.Model
	Name      string
	Age       uint
}

type UserMixin struct {
	UserID uint
	User User `gorm:"foreignKey:UserID"`
}

type Company struct {
	gorm.Model
	UserMixin
	ID   int
	Name string
}

func TestGORM(t *testing.T) {
	user := User{Name: "jinzhu"}

	DB.Create(&user)

	company := Company{Name: "jinzhu's company", UserMixin: UserMixin{UserID: user.ID}}

	DB.Create(&company)

	var companyResult Company
	if err := DB.Preload(clause.Associations).First(&companyResult, company.ID).Error; err != nil {
		t.Errorf("Failed, got error: %v", err)
	}
}

Before fix:

Screenshot 2024-04-09 at 03 03 29

After fix:

image

@yetone
Copy link
Copy Markdown
Contributor Author

yetone commented Apr 9, 2024

I have successfully tested it locally, the CI failure appears to be due to the container failing to start.

image

@jinzhu jinzhu merged commit 9a61ef2 into go-gorm:master Apr 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants