My database structure contains the following fields: catalog.id
, catalog.category_id
, catalog.name
and its related field, category.name
and category.id
.
While importing csv records containing fields of csv_category_name
and csv_catalog_name
using golang, as the loop starts I want to check if csv_category_name
exists in the field category.name
and return its value to be inserted in catalog.category_id
otherwise, create a category.name
and return category.id
retain the value in the memory so it can be inserted into catalog.cateogory_id in the rest of the loop with a similar condition before the loop continues
i believe there could be an easier way but with my limited knowledge in golang, I have drafted a code and i believe with your suggestion i can provide a better result
package main
import (
"io"
"log"
)
func main() {
cname := models.Category{
CategoryName: c.Name, // this to be picked from loop
}
bb, err := models.CategoryByID(db, 4)
if err != nil {
cname.Save(db)
return cname
}
for {
var c CatalogCSV
//CheckorCreate when the loop starts and use the value in the rest of the loop
if err := dec.Decode(&c); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
a := models.Catalog{
CatalogName: c.Catalogname,
CatalogCategoryName: c.Categoryname, // This is part of the initial CSV file
CataloCategoryID: b.ID, // this is to be picked from CategoryByID
}
// save author to database
err = a.Save(db)
if err != nil {
log.Fatal(err)
}
}
}