1

gorm を使用して、構造体からデータベースへのマッピングを管理しています。現在、API にラップしようとしている既存のスキーマがあります。問題は、構造体の 1 つにmany2many、デフォルトの列名を使用しない別のテーブルを介した結合があることです。

golang コード

type AuthUser struct {
  ID          *int
  Username    *string `sql:"size:30"`
  FirstName   *string `sql:"size:30"`
  LastName    *string `sql:"size:30"`
  Email       *string `sql:"size:75"`
  IsActive    *bool
  IsStaff     *bool
  IsSuperuser *bool
  DateJoined  *time.Time
  LastLogin   *time.Time
  //ReviewsGroups ReviewsGroups `gorm:"foreignkey:group_id;associationforeignkey:user_id;many2many:reviews_group_users"`
  //ReviewsGroups ReviewsGroups `gorm:"many2many:reviews_group_users"`
  ReviewsGroups []ReviewsGroup `gorm:"many2many:reviews_group_users"`
}

type ReviewsGroups []ReviewsGroup


func (app *AppEnv) FindAuthUser(username string) (*AuthUser, error) {
  var user AuthUser
  //var groups []ReviewsGroup
  //err := app.DB.Where(&AuthUser{Username: &username}).First(&user).Related(&groups).Error
  err := app.DB.Preload("ReviewsGroups").Where(&AuthUser{Username: &username}).First(&user).Error
  return &user, err
}

テーブルに参加

rb=> \d reviews_group_users
                          Table "public.reviews_group_users"
  Column  |  Type   |                            Modifiers
----------+---------+------------------------------------------------------------------
 id       | integer | not null default nextval('reviews_group_users_id_seq'::regclass)
 group_id | integer | not null
 user_id  | integer | not null
Indexes:
    "reviews_group_users_pkey" PRIMARY KEY, btree (id)
    "reviews_group_users_group_id_user_id_key" UNIQUE CONSTRAINT, btree (group_id, user_id)
    "reviews_group_users_group_id" btree (group_id)
    "reviews_group_users_user_id" btree (user_id)
Foreign-key constraints:
    "group_id_refs_id_0f32ed01" FOREIGN KEY (group_id) REFERENCES reviews_group(id) DEFERRABLE INITIALLY DEFERRED
    "reviews_group_users_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED

結果のクエリ出力

[2015-10-30 09:31:32]  [1.16ms]  SELECT  * FROM "auth_user"  WHERE ("username" = 'theuser') ORDER BY "auth_user"."id" ASC LIMIT 1
[2015-10-30 09:31:32]  [1.85ms]  SELECT  * FROM "reviews_group" INNER JOIN reviews_group_users ON reviews_group_users."reviews_group_id" = "reviews_group"."id" WHERE (auth_user_id in ('13'))
[2015-10-30 09:31:32]  pq: column reviews_group_users.reviews_group_id does not exist

どんな助けでも大歓迎です。

ありがとう!

4

0 に答える 0