yikegaya’s blog

仕事関連(Webエンジニア)と資産運用について書いてます

GoのORマッパーBunでRelation先のモデルが取得できないエラーの対応

GoのORマッパー bunでmodelに定義したRelationモデルが取得できなかった時の地味に気づきにくかった対応メモ。

1つのAccountに複数Userを登録できるサービスのテーブルを例に書きます。

モデル定義

type User struct {
    bun.BaseModel `bun:"table:users"`

    ID         int64                        `bun:"id,pk,autoincrement" json:"id"`
    AcountID  int64                        `bun:"account_id,notnull" json:"account_id"`

    Account *Account `bun:"rel:belongs-to,join:account_id=id" json:"account,omitempty"`
}

これはダメ(User.Accountがnullになる

 err := r.db.
        NewSelect().
        Model(User).
        Join("JOIN accounts ON accounts.id = user.account_id").
        Scan(ctx)

JoinではなくRelationで書くと取れる

 err := r.db.
        NewSelect().
        Model(User).
        Relation("Account").
        Scan(ctx)