【已解决】Laravel paginate()分页后 出现数据重复 或 数据丢失问题
问题情景描述:
- 已知有一张学生表与一张消费积分表。现根据每个学生的消费积分对学生表进行正序排列(即积分从高到低排列)。
- 学生表students 与 消费积分表orders表为一对多关系(一条学生数据 对应 多条投票积分数据)。
数据表格示例
学生表(students)
消费积分表(orders)
id | vote(投票) | students_id(学生表id) | is_pay(是否支付) |
---|
1 | 2 | 1 | 1 | 2 | 3 | 3 | 1 | 3 | 4 | 1 | 0 | 4 | 5 | 2 | 1 | 5 | 2 | 1 | 1 | 6 | 1 | 2 | 1 | 7 | 3 | 2 | 1 | 8 | 2 | 1 | 1 | 9 | 6 | 3 | 1 |
错误代码示例
此时获取的数据后前端使用laravel自带的分页$data->links();会发生丢失数据 或者数据重复的问题
public function studentList(Request $request){
$data = Student::select('students.*',DB::raw('(SELECT SUM(contribution_value) FROM orders WHERE orders.students_id = students.id and orders.is_pay = 1) as sum_contribution_value'))
->orderBy('sum_contribution_value','desc')
->paginate(10);
return view('h5.student.studentList',compact('data'));
}
错误数据渲染后的示例图:  
解决方案:
正确代码示例:
public function studentList(Request $request){
$data = Student::select('students.*',DB::raw('(SELECT SUM(contribution_value) FROM orders WHERE orders.students_id = students.id and orders.is_pay = 1) as sum_contribution_value'))
->orderBy('sum_contribution_value','desc')
>orderBy('students.id','desc')
->paginate(10);
return view('h5.student.studentList',compact('data'));
}
返回数据出现丢失或重复的原因
由上述错误代码示例中所示:->orderBy('sum_contribution_value','desc') 仅使用了这此标识进行排序,但此表示不是对整个返回的数据而言不是唯一标识! Mysql使用order by排序时因为排序标识不唯一,所以每次查询数据的顺序不一样,导致分页截取的数据片段有重复数据或造成数据丢失。 所以加入最后在用唯一标识字段进行下排序即可(比如表的唯一id或者订单编号之类的带有唯一约束的字段)。
|