I created 2 model: User and Order. Assuming a one-to-many relationship between User and Order like the following:
type User struct {
ID uint
Name string
Orders []Order // Assuming a one-to-many relationship between User and Order
}
type Order struct{
ID uint
UserID uint
User User
}
I created UserDTO for response data for Front End like the following:
type UserDTO{
Name string
Orders []Order
}
Then I want to preload Orders from User and scan query result to UserDTO:
var userDTO UserDTO
// Preload the "Orders" association and scan into the UserDTO struct
db.Model(&User{}).Preload("Orders").Where("id = ?", userID).Find(&userDTO)
With this query above it raise a error: invalid field found for struct UserDTO's field Orders: define a valid foreign key for relations or implement the Valuer/Scanner interface
I know I can do with the way:
var user User
db.Model(&User{}).Preload("Orders").Where("id = ?", userID).Find(&user)
and then convert user from User type to UserDTO type.
But I want to know that with previous way whether GORM can support and let me know how to fix the error above?
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨