Following is the struct of the Genre Model :
type Genre struct {
ImageId int
GenreType string
}
I am executing the following query for finding all the genreTypes for an ImageId. The code is as follows:
func getGenresOfImage(DB *gorm.DB, w http.ResponseWriter, imageId int) ([]string, error) {
var genres []string
var allGenres []models.Genre
genresOfCurrentImage := DB.Where("ImageId = ?", strconv.Itoa(imageId)).Find(&allGenres)
genreRows, err := genresOfCurrentImage.Rows()
if err != nil {
SendErrorResponse(w, http.StatusInternalServerError, err.Error())
return genres, err
}
var genre models.Genre
for genreRows.Next() {
DB.ScanRows(genreRows, &genre)
genres = append(genres, genre.GenreType)
}
return genres, nil
I am getting the following error:
Images.go:46 no such column: ImageId
[0.908ms] [rows:0] SELECT * FROM `genres` WHERE ImageId = "1"
Is the syntax that I am using wrong for finding the all the genres associated with an imageId? Any help is appreciated!
CodePudding user response:
Most likely your column name will be image_id.
As the gorm documentation says:
Column db name uses the field’s name’s snake_case by convention.
The tables get generated this way when you use gorm's auto migrate feature.
For further info see: https://gorm.io/docs/conventions.html#Column-Name
CodePudding user response:
If you look at the default naming strategy here, you can see that the image_id column name is expected in the query (assuming that image_id is the name of your column in the database).
with this in mind, there are few options you can try out:
Use image_id in the Where method:
DB.Where("image_id = ?", strconv.Itoa(imageId)).Find(&allGenres)
Use struct to pass the condition to the Where method:
DB.Where(&models.Genre{ ImageID: imageId}).Find(&allGenres)
Or, if your column in the database is actually named ImageId, you can add this to the models.Genre struct:
type Genre struct {
// other fields
ImageID int `gorm:"column:ImageId"`
}
