Skip to content

How can I preload with specific Model? #6772

Answered by iTanken
plusiv asked this question in Q&A
Discussion options

You must be logged in to vote

At least ID field and foreignKey tag are required.

type User struct {
	gorm.Model
	Username string
-	Orders   []Order
+	Orders   []Order `gorm:"foreignKey:UserID;references:ID"`
}

type CustomUserRes struct {
+	ID       uint                            `gorm:"primaryKey"`
	Username string                          // <--- No gorm default fields required
-	Orders   []Order
+	Orders   []Order `gorm:"foreignKey:UserID;references:ID"`
}

var user User
var userCustom CustomUserRes
var ordersCustom CustomOrderRes

db.Preload("Orders", func (tx *gorm.DB) *gorm.DB {
-  return tx.Scan(&ordersCustom) // <--- I want to fit the preload result to ordersCustom
+  return tx.Model(&Order{}).Scan(&ordersCus…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by plusiv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants