gogo-gorm

Is there a way to get the full number of results using GORM?


I'm currently writing a query with GORM, and I need to display a pagination information with the results.

In order to generate the pagination, I need the number of results that my query would return if I didn't use the Limit() clause. (Like in "showing results 11 to 20 out of 154").

How can I get this value ? Do I have to make two different queries ?


Solution

  • I found a nice way to prevent writing (and maintaining) two different queries:

    var total int64
    var myStructVar MyStruct
    
    DB.
    Table("my_table"). // could have been Model(MyStruct{})
    // My query stuff
    Limit(10).
    Offset(40).
    Find(&myStructVar).
    Limit(-1). // To reset the limit
    Count(&total)
    

    This way, two different queries are made and I have both my result, and my total number of lines.