[英]Rust diesel Postgres how to add pagination to query
I am using the diesel to connect and fetch data from the Postgres database.我正在使用柴油连接并从 Postgres 数据库中获取数据。 I want to use pagination to fetch a large number of records from my database into a few records at a time.我想使用分页一次将大量记录从我的数据库中提取到几条记录中。 Let's say I have 1000 records of data, I need to fetch 20 data at a time with a total number of records.假设我有 1000 条数据记录,我需要一次获取 20 条数据,总记录数。 Below is my table and I have used the inner join to fetch data.下面是我的表,我使用了内部连接来获取数据。
#Emplyee table
| employee-id | employee_name | empolyee_email|
| ----------- | --------------|------------- |
| 1 | ABC |abc@mail.com |
| 2 | xyz |xyz@mail.com |
# Account table
| account | employee-id | account-balnce | created_at|
| -------- | ---------- |--------------- |-----------|
| 1 | 1 | 2000 | 22/10/2021|
| 2 | 2 | 5000 | 01/09/2021|
Query which I used to fetch data.我用来获取数据的查询。
let employee_account = employee::table
.inner_join(account::table.on(employee::dsl::employee_id.eq(account::dsl::employee_id)),)
.filter(account::dsl::employee_id.eq(employeeId))
.load::<(Employee_Details,)>(&self.pool.get()?)?;
I explored the Diesel doc and find the limit
( doc ) and offset
( doc ) functions look promising for implementing pagination.我探索了 Diesel 文档,发现limit
( doc ) 和offset
( doc ) 函数看起来很有希望实现分页。 Please try to add these two functions before the load
function like below.请尝试在load
function 之前添加这两个函数,如下所示。 Initialize page_size with 20 and offset with 0. Loop until no data returns.用 20 初始化 page_size,用 0 初始化偏移量。循环直到没有数据返回。 Increase the offset by the page size for next load.为下次加载增加页面大小的偏移量。
let page_size = 20;
let mut offset = 0;
let employee_account = employee::table
.inner_join(account::table.on(employee::dsl::employee_id.eq(account::dsl::employee_id)),)
.filter(account::dsl::employee_id.eq(employeeId))
.limit(page_size)
.offset(offset)
.load::<(Employee_Details,)>(&self.pool.get()?)?;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.