'Preload() custom JoinTable Gorm.io for SQL-SELECT

I just do have a question about Gorm.io for Go:

I do have a nested DB-Struct with custom JoinTable (M2M).

With my SQL-Select I'd like to Preload() the full data from custom JoinTable. But I didn't get it working so far.

My DB:

var Db *gorm.DB

type Players struct {
    Player_ID              int         `gorm:"primaryKey;index"`
    UserName               string
    Is_Online              bool
    Ready                  bool
}
type Game struct {
    Game_ID                int         `gorm:"primaryKey;index"`
    Players                []Players   `gorm:"many2many:game_players"`
}

// Custom JoinTable
type GamePlayers struct {
    Game_Game_ID           int         `gorm:"primaryKey;index"`
    Players_Player_ID      string      `gorm:"primaryKey;index"`
    TablePlaceNumber       int
}

func main(){
    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }
    Db = db
    
    Db.SetupJoinTable(&Game{}, "Players", &GamePlayers{})

    Db.AutoMigrate(&Players{}, &Game{})
}

My Select (select Game by a Player and show all Players from the Game):

var game Game
// for better reading, I removed quotes for String
const sqlSelectCurrentGame = SELECT *
  FROM games
  INNER JOIN game_players ON game_players.game_game_id = games.game_id
  INNER JOIN players ON game_players.players_pk_player_id = players.pk_player_id
  WHERE games.game_id = (SELECT games.game_id
    FROM games
    INNER JOIN game_players ON game_players.game_game_id = games.game_id
    WHERE game_players.players_player_id = 1)
  ORDER BY game_players.table_place_number ASC

Db.Raw(sqlSelectCurrentGame).Preload("Players").Find(&game)

The Select does returning the structure Game with array of participating Game-Players as nested Players-struct with Players-attributes.

But my goal is to get the data from custom JoinTable GamePlayers as well.

Is there a possibility, to reach my goal?

Thank you an BR Phil



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source