pilagod / gorm-cursor-paginator

A paginator doing cursor-based pagination based on GORM
https://github.com/pilagod/gorm-cursor-paginator
MIT License
188 stars 44 forks source link

Using smart select fields #57

Closed dschreij closed 8 months ago

dschreij commented 8 months ago

Gorm allows you to provide a different struct for data selection/population, if you provide the struct that specifies the table to select from in Model() (docs). For instance, on some occasions, I 'enrich' my model structs with composition to allow adding extra meta fields, e.g.

type UserWithPostCount struct {
    User
    PostCount `json:"post_count"`
}

var results *UserWithPostCount
tx := db.Model(User{}).
     Select("users.*, count(*) as post_count").
     Join("posts on users.id = posts.user_id").
     Group("users.id").
     Find(&results)

this works in basic Gorm, where post_count will have the value specified in the select statement and the origin table is defined by Model(User).

I hoped the same would be possible with the Paginate() function, by passing the UserWithPostCount as the destination struct, but if I try this, I get the error that the table "user_with_post_count" does not exist.

Would it be possible to let the Model() or Table() call specify the table to query, and not let the destination struct passed to Paginate() define this?

pilagod commented 8 months ago

Have you tried custom table name or scoping, mentioned in this document?

https://gorm.io/docs/conventions.html#TableName

Underlying the paginator, it will leverage gorm.Statement to parse table name from dest model, like the code shown below:

https://github.com/pilagod/gorm-cursor-paginator/blob/f807e66213b074b491dff8cf5e7fc3040f9768df/internal/util/model.go#L8-L14

So I'm optimistic that custom table name or scoping might be helpful.

dschreij commented 8 months ago

Using TableName() works! Thank you very much :)