Skip to content

Executing count will clear Statement.Joins #7025

@liov

Description

@liov

go-gorm/playground#736

type AB struct {
	Id  int `json:"id" gorm:"primaryKey"`
	BId int `json:"aId" gorm:"index"`
	AId int `json:"bId"`
	B   B   `json:"b"`
	A   A   `json:"a"`
}

type A struct {
	Id   int    `json:"id" gorm:"primaryKey"`
	Name string `json:"name" gorm:"uniqueIndex"`
}

type B struct {
	Id   int    `json:"id" gorm:"primaryKey"`
	Name string `json:"name" gorm:"uniqueIndex"`
}

func main() {
	db, _ := gorm.Open(tests.DummyDialector{}, &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})

	var (
		count    int64
		appNodes = []*AB{}
	)
	db:= db.Model(&AB{}).Joins("A").Joins("B").Where(`id = ?`, 1)

	db.Count(&count)
	db.Limit(1).Offset(0).Order("id DESC").Find(&appNodes)
}
db := db.Model(&AB{}).Preload("A").Preload("B").Where(`id = ?`, 1)

The two pieces of code have different results, preload will get the correct result, because Count will call AfterQuery,it will "clear the joins after query because preload need it" ,I don't know why did it, this means need to write Joins twice.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions