'No such column, SQLite GORM

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())
        // error is returned here
        return genres, err
    }
    

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!



Solution 1:[1]

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"`
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emin Laletovic