0
votes

I have User & Profile (one-to-one belongs to User)

type User struct {
   ID          int
   Username    string
   Password    string
}

type Profile struct {
   Fullname    string
   Address     string
   UserID      int
   User        User
}

If I know the User I can find the related Profile by db.Model(&user).Related(&profile). How if I want to query multiple users, and I also need the related profiles? If I use the same method I will get n+1 problem. Any clue will be appreciated.

1

1 Answers

-1
votes

You can write a plain query using Raw() method:

type VwStruct struct{
   ID       string
   Username string
   Password string
   Address  string
   Fullname string
}

var YourStruct *VwStruct
db.Raw('SELECT u.*, p.Fullname AS user_full_name, p.Address AS user_address FROM user u INNER JOIN profile p ON u.ID = p.UserId').scan(&YourStruct)

Good luck!