Как загрузить структуры с несколькими вложенными ассоциациями - PullRequest
1 голос
/ 06 марта 2020

Я пытаюсь загрузить один в один и один ко многим ассоциациям для одного из моих объектов, используя GORM. Я продолжаю получать следующую ошибку при попытке запустить.

{
    "errors": [
        {
            "message": "can't preload field UserProfiles for models.Renter",
            "path": [
                "users"
            ]
        }
    ],
    "data": null
}

Вот мой код

type User struct {
    BaseModelSoftDelete        // We don't to actually delete the users, audit
    Email               string `gorm:"not null;unique_index"`
    Password            string
    FirstName           *string
    LastName            *string
    Renter              Renter        `gorm:"auto_preload"`
    Rentee              Rentee        `gorm:"auto_preload"`
    UserProfiles        []UserProfile `gorm:"association_autocreate:false;association_autoupdate:false"`
    Roles               []Role        `gorm:"many2many:user_roles;association_autocreate:false;association_autoupdate:false"`
    Permissions         []Permission  `gorm:"many2many:user_permissions;association_autocreate:false;association_autoupdate:false"`
}

// UserProfile saves all the related OAuth Profiles
type UserProfile struct {
    BaseModelSeq
    Email          string    `gorm:"unique_index:idx_email_provider_external_user_id"`
    UserID         uuid.UUID `gorm:"not null;index"`
    User           User      `gorm:"association_autocreate:false;association_autoupdate:false"`
    Provider       string    `gorm:"not null;index;unique_index:idx_email_provider_external_user_id;default:'DB'"` // DB means database or no ExternalUserID
    ExternalUserID string    `gorm:"not null;index;unique_index:idx_email_provider_external_user_id"`              // User ID
    Name           string
    FirstName      string
    LastName       string
    AvatarURL      string `gorm:"size:1024"`
    Description    string `gorm:"size:1024"`
}

type Renter struct {
    BaseModelSoftDelete           // We don't to actually delete the users, audit
    UserID              uuid.UUID `gorm:"unique;not null;index"`
    Verified            bool
    Properties          []Property `gorm:"association_autocreate:false;association_autoupdate:false"`
    Listings            []Listing  `gorm:"association_autocreate:false;association_autoupdate:false"`
}

type Rentee struct {
    BaseModelSoftDelete           // We don't to actually delete the users, audit
    UserID              uuid.UUID `gorm:"unique;not null;index"`
    Verified            bool
    Bookings            []Booking `gorm:"association_autocreate:false;association_autoupdate:false"`
}


, тогда я вызываю эту функцию

func userList(r *queryResolver, id *string) (*gql.Users, error) {
    entity := consts.GetTableName(consts.EntityNames.Users)
    whereID := "id = ?"
    record := &gql.Users{}
    dbRecords := []*dbm.User{}
    tx := r.ORM.DB.Begin().Preload(consts.EntityNames.UserProfiles)
    defer tx.RollbackUnlessCommitted()
    if id != nil {
        tx = tx.Where(whereID, *id)
    }
    tx = tx.Find(&dbRecords).Count(&record.Count)
    for _, dbRec := range dbRecords {
        renter := dbm.Renter{}
        tx = tx.Model(&dbRec).Related(&renter)
        logger.Infof("%+v", dbRec.Renter)
        // rentee := dbm.Rentee{}
        // tx.Related(&rentee)
        // logger.Info(rentee)
        if rec, err := tf.DBUserToGQLUser(dbRec); err != nil {
            logger.Errorfn(entity, err)
        } else {
            record.List = append(record.List, rec)
        }
    }
    return record, tx.Error
}

Если Я избавляюсь от tx = tx.Model(&dbRec).Related(&renter), когда запрос выполняется, объект профиля загружается, но у моего объекта съемщика и арендатора нет данных из базы данных. И я замечаю, что он не запускает запрос SELECT * FROM "renters" WHERE "renters"."deleted_at" IS NULL AND (("user_id" = 'my-user-uuid'))

Я также пытался это так:

tx = tx.Preload(consts.EntityNames.Renters).Preload(consts.EntityNames.Rentees).Preload(consts.EntityNames.UserProfiles).Find(&dbRecords).Count(&record.Count)

, но получаю эту ошибку: can't preload field Renters for models.User

...