-
| Having the follow example: type User struct {
  gorm.Model
  Username string
  Orders   []Order
}
type CustomUserRes struct {
  Username string // <--- No gorm default fields required
  Orders   []Order
}
type Order struct {
  gorm.Model
  UserID uint `json:"user_id"`
  Price  float64
  Detail string
}
type CustomOrderRes {
  UserID uint `json:"user_id_custom"` // <--- Custom json key name
  Price  float64
  // Detail string <--- Notice that Detail Attribute is not required here
}How can I query a  I tried something like but didn't work: var user User
var userCustom CustomUserRes
var ordersCustom CustomOrderRes
db.Preload("Order", func (tx *gorm.DB) *gorm.DB {
  return tx.Scan(&ordersCustom) // <--- I want to fit the preload result to ordersCustom
}).Model(&user{}).First(&userCustom) | 
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            iTanken
          
      
      
        Jan 3, 2024 
      
    
    Replies: 1 comment
-
| At least  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(&ordersCustom) // <--- I want to fit the preload result to ordersCustom
}).Model(&user).First(&userCustom) | 
Beta Was this translation helpful? Give feedback.
                  
                    0 replies
                  
                
            
      Answer selected by
        plusiv
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
At least
IDfield andforeignKeytag 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…