3

I want to execute a query like below in golang gorm:

select * from MY_TABLE where MY_FIELD in (select max(MY_FIELD) as MY_FIELD from MY_TABLE group by ANOTHER_FIELD)

Is there a way besides raw query in gorm?

1
  • Would be nice to have the data type structure Commented Nov 17, 2017 at 8:19

2 Answers 2

4

You can do this by building up your query. Check out this example:

func FindProspects(categories *string, cities *string, hasEmail *bool, hasContactperson *bool, limit int64, offset int64) []*gModels.Prospect {
    var prospects []*gModels.Prospect

    query := env.DB().Table("prospects").Select("prospects.id, prospects.name")

    if categories != nil {
        query = query.Joins("JOIN prospect_categories ON prospect_categories.prospect_id = prospects.id").Where("prospect_categories.category_name IN (?)", strings.Split(*categories, ","))
    }

    if cities != nil {
        query = query.Where("prospects.city IN (?)", strings.Split(*cities, ","))
    }

    if hasEmail != nil && *hasEmail == true {
        query = query.Where("prospects.id IN (SELECT emails.prospect_id FROM emails WHERE emails.prospect_id = prospects.id)")
    }

    if hasContactperson != nil && *hasContactperson == true {
        query = query.Where("prospects.id IN (SELECT contact_people.prospect_id FROM contact_people WHERE contact_people.prospect_id = prospects.id)")
    }

    query = query.Order("prospects.name ASC")

    query.Limit(int(limit)).Offset(int(offset)).Find(&prospects)

    return prospects
}

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

you can build raw queries

subQuery := db.Model(Table_Name).Select(field).Group(field).QueryExpr()

err := db.Model(TableName).Scan(outPutStructArray).Where("myfiled IN (?)", subQuery).Error

and handle error appropriately

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.