2

I have a struct called Ads

type Ads struct {
    ID      int `json:"id"`
    Subject string `json:"subject"`
    Phone   string `json:"phone"`
}

func GetAdsPostgres() (ads []Ads, err error) {
    ads = make([]Ads, 0)
    rows, err := db1.Query("Select ad_id, subject FROM ads limit 200 ")
    for rows.Next() {
        var ad Ads
        rows.Scan(&ad.ID, &ad.Subject)

        test := reflect.ValueOf(ad.ID)
        addd := test.Interface().(int)
        rows1, _ := db1.Query("Select phone FROM ads where ad_id=$1", addd)
        rows1.Scan(&ad.Phone)

        ads = append(ads, ad)
        rows1.Close()
    }

    if err = rows.Err(); err != nil {
        return
    }
    return
}

without thinking of join the table because the phone has multipte enumeration values which I have to reform them as fields after

3
  • Your if err = rows.Err(); err != nil { return } is entirely unnecessary. No need for an if ... { return } return. Just do return. Apr 11, 2018 at 9:38
  • @Flimzy for the phone is having an enumeration value : local , regional , international with each value so i created a struct having all the fields with the phone enumeration that's why i have to follow this method
    – dev_medo
    Apr 11, 2018 at 10:23
  • @dev_medo: That's irrelevant to my point. Having an "if x do y else do y" is identical to just "y" Apr 11, 2018 at 10:27

1 Answer 1

3

Just get the phone number too in the first query; don't repeat yourself.

db1.Query("Select ad_id, subject, phone FROM ads limit 200 ")
1
  • for the phone is have an enumeration value : local , regional , international with each value so i created a struct having all the fields with the phone enumeration that's why i have to follow this method
    – dev_medo
    Apr 11, 2018 at 10:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.