1

I use GORM and I paginate my data. I get n rows each time. Unfortunately I need to compare row with previous one. Is there a way in GORM to fetch exclusive n rows and one from previous call? When I set offset to n+1 it does not get that one previous row.

Example:

// page=1 limit=3

[
  {
    "id": 1,
    "A": 12,
    "B": 434,
  },
  {
    "id": 2,
    "A": 456,
    "B": 786,
  },
  {
    "id": 3,
    "A": 23,
    "B": 978,
  }
]

// ... compare if A is equal in previous object and
return [{
    "id": 1,
    "A": 12,
    "B": 434,
    "isGreater": false,
  },{
    "id": 2,
    "A": 456,
    "B": 786,
    "isGreater": true,
  },{
    "id": 3,
    "A": 23,
    "B": 978,
    "isGreater": false,
  }]

and

// page=2 limit=3
// from db fetch 4 rows
[
  {
    "id": 3,
    "A": 12,
    "B": 434,
  },
  {
    "id": 4,
    "A": 456,
    "B": 786,
  },
  {
    "id": 5,
    "A": 23,
    "B": 978,
  },
  {
    "id": 6,
    "A": 23445,
    "B": 978,
  }
]

// but return only 3
return [{
    "id": 4,
    "A": 12,
    "B": 434,
    "isGreater": false,
  },{
    "id": 5,
    "A": 456,
    "B": 786,
    "isGreater": true,
  },{
    "id": 6,
    "A": 23,
    "B": 978,
    "isGreater": true,
  }]
Nju
  • 579
  • 1
  • 8
  • 18

1 Answers1

0

You could use Custom Preloading SQL, to set offset with a limit number record to retrieve.

Sample codes

db.Preload("Orders", func(db *gorm.DB) *gorm.DB { 
    return db.Offset(0).Limit(10)
})

Update

Another option for paginate is to use the FindByPage of GORM Gen

func (m mytableDo) FindByPage(offset int, limit int) (result []*model.Mytable, count int64, err error) {
    count, err = m.Count()
    if err != nil {
        return
    }

    result, err = m.Offset(offset).Limit(limit).Find()
    return
}
zangw
  • 43,869
  • 19
  • 177
  • 214
  • I have message `Data: unsupported relations for schema Data`. And if I understand documentation correctly Preload is not for this purpose. – Nju Oct 14 '22 at 12:53
  • @Nju, https://stackoverflow.com/questions/66810464/unsupported-relations-in-gorm, https://stackoverflow.com/questions/67303897/unsupported-relations-for-schema, https://stackoverflow.com/questions/67579704/unsupported-relations-in-gorm-nested-preload. Hope those related question could help you – zangw Oct 14 '22 at 14:08
  • I saw it. It is not my case. I have one table `Data` with two columns – Nju Oct 14 '22 at 15:16