go-gorm如何在其他查询中使用“不在哪里”查询

时间:2018-11-22 08:12:49

标签: go-gorm

我需要查询“ Where(“ users.user_id NOT IN(?)”,pr)。”其中pr是来自另一个查询“ db.Table(” partner_relationships“)。Select(” partner_id“)。Where(” user_id =?“,guid).Find(&pr)”

的结果。

func GetAllBusinessPartners(db *gorm.DB, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
guid := vars["id"]
results := []model.BusinessPartner{}
pr := []model.PartnerRelationship1{}

db.Table("partner_relationships").Select("partner_id").Where("user_id = ?", guid).Find(&pr)

db.Table("users").Select("users.user_id, users.first_name, users.last_name, users.profile_image, business_informations.title, business_informations.business_name").
    Joins("JOIN business_informations ON users.user_id = business_informations.user_id").
    Where("users.user_id != ?", guid).
    Where("users.user_id NOT IN (?)", pr).
    Scan(&results)
respondJSON(w, http.StatusOK, results)}

type User struct {
    gorm.Model
    UserID         uuid.UUID       `gorm:"type:uuid" json:"userID"`
    FirstName      string          `json:"firstName"`
    LastName       string          `json:"lastName"`
    Gender         string          `json:"gender"`
    Birthday       time.Time       `json:"birthday"`
    ProfileImage   string          `json:"profileImage"`
}


type BusinessPartner struct {
    ID           uint      `json:"id"`
    UserID       uuid.UUID `json:"userID"`
    FirstName    string    `json:"firstName"`
    LastName     string    `json:"lastName"`
    ProfileImage string    `json:"profileImage"`
    Title        string    `json:"title"`
    BusinessName string    `json:"businessName"`
}

type PartnerRelationship struct {
    gorm.Model
    UserID       uuid.UUID `gorm:"type:uuid" json:"userID"`
    PartnerID    uuid.UUID `gorm:"type:uuid" json:"partnerID"`
    Status       uint      `json:"status"`
    ActionUserID uuid.UUID `gorm:"type:uuid" json:"actionUserID"`
}

1 个答案:

答案 0 :(得分:0)

找到解决方案必须将结构转换为字符串

func GetAllBusinessPartners(db *gorm.DB, w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    guid := vars["id"]
    results := []model.BusinessPartner{}

    pr := []model.PartnerRelationship{}
    db.Table("partner_relationships").Select("partner_id").Where("user_id = ?", guid).Find(&pr)

    var s []string
    for _, v := range pr {
        s = append(s, v.PartnerID.String())
    }
    fmt.Printf("%q\n", s)

    db.Table("users").Select("users.user_id, users.first_name, users.last_name, users.profile_image, business_informations.title, business_informations.business_name").
        Joins("JOIN business_informations ON users.user_id = business_informations.user_id").
        Where("users.user_id != ?", guid).
        // Where("users.user_id NOT IN (?)", []string{"fbfda7f4-3691-44d0-89f2-8ccdaf3abe88", "12caf34b-42d0-4ac7-a347-a6ae1a88cb43"}).
        Where("users.user_id NOT IN (?)", s).
        Scan(&results)
    respondJSON(w, http.StatusOK, results)
}