我有 2 个表,分别命名收入和支出,我想使用 Laravel 分页在一个 View 中显示所有数据。为此,我使用 array_merge() 合并了两个数组。
$incomes = Income::where('user_id', Auth::User()->id)->get()->toArray();
$expenses = Expense::where('user_id', Auth::User()->id)->get()->toArray();
foreach ($incomes as $key => $value) {
$incomes[$key]['type'] = 'income';
}
foreach ($expenses as $key => $value) {
$expenses[$key]['type'] = 'expense';
}
$results = array_merge($incomes, $expenses);
如何对这个$结果进行分页?
最佳答案
您可以通过两种方式执行此操作:
- Laravel 内置手动创建分页器功能。
- 使用 UNION 从表中获取结果。
使用联合
$incomes = Income::where('user_id', Auth::User()->id);
$data = Expense::where('user_id', Auth::User()->id)->union($incomes)->paginate(10);
要手动创建分页器,请参阅 https://laravel.com/docs/6.x/pagination#manually-creating-a-paginator
将以下内容添加到收入模型
protected $appends = ['type'];
public function getTypeAttribute()
{
return 'Income';
}
将以下内容添加到费用模型
protected $appends = ['type'];
public function getTypeAttribute()
{
return 'Expense';
}
这将在查询结果中添加类型键。
关于php - Laravel 使用 array_merge 进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59562525/