0
0

GORMで特定のフィールドのみ選択(select)したとき、mapを使用してクエリ結果を取得する方法

Posted at

はじめに

GORMを使用してデータベースからデータを取得する際、しばしば特定のフィールドのみを選択したい場合があります。
通常、これはカスタム構造体を定義し、その構造体へスキャンすることでデータを取得しますが、カスタム構造体の定義がめんどくさい場合、簡易的にmapを使用することでも取得が可能です。

type User struct {
    ID       uint
    Name     string
    Email    string
    Age      int
}

type Order struct {
    ID          uint
    UserID      uint
    ProductName string
    Quantity    int
    TotalPrice  float64
}

// mapを使用し、ここにスキャンする
var results []map[string]interface{}

// 2つのテーブルをjoinして特定のカラムを選択する
err := db.Table("users").
    Select("users.name, orders.total_price").
    Joins("JOIN orders ON orders.user_id = users.id").
    Scan(&results).Error
if err != nil {
    fmt.Printf("failed to execute query: %v", err)
}

// 結果の表示
for _, result := range results {
    fmt.Printf("Name: %v, Total Price: %v\n",
        result["name"],
        result["total_price"]
    )
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0