1
0

More than 1 year has passed since last update.

Goでモデルのカラムを配列として定義したい

Last updated at Posted at 2022-12-20

はじめに

モデルの一部のカラムを配列で定義する際、テーブル作成が出来ずに詰まったので解決までの流れを簡単にまとめてみます

①pqパッケージのStringArrayで定義すると

Catalog.go
import "github.com/lib/pq"

type Catalog struct {
	gorm.Model
	Title     string `gorm:"not null"`
	Comments    pq.StringArray

以下を参考にしましたが、こちらはPostgreSQL用でした

今回使用しているのはMySQLなので以下のエラーが発生し、テーブル作成ができませんでした

Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[], ... at line 1

次はこちらの記事を参考にしました

記事では以下の解決策が書かれていました

  1. 配列を文字列かバイト型で定義する
  2. 2つのテーブルを作成して紐づける

②配列を文字列かバイト型で定義すると

type Catalog struct {
	gorm.Model
	Title     string `gorm:"not null"`
	Comments    string[]

すると以下のエラーが発生しました

[error] unsupported data type: &[]

③【解決】Commentモデルを作成し、Catalogモデルに紐づけをすると

Comment.go
import "gorm.io/gorm"

type Comment struct {
	gorm.Model
	Content string `gorm:"not null" json:"content"`
	CatalogID uint 
}
Catalog.go
type Catalog struct {
	gorm.Model
	Title     string `gorm:"not null"`
	Comments    []Comment

最終的にこの方法でテーブル作成ができました

gormのhas manyの書き方は公式ドキュメントを参考にしました

おわりに

gormに早く慣れていきたいです。

1
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
1
0