[英]Laravel Pagination with array_merge
I have 2 table which name incomes and expenses and I want to show all the data in one view with laravel pagination.我有 2 个表,分别命名收入和支出,我想用 laravel 分页在一个视图中显示所有数据。 For this, I Merged two array with array_merge().为此,我使用 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);
How can I paginate this $results?我怎样才能对这个 $results 进行分页?
You can do this in two ways:您可以通过两种方式执行此操作:
Using UNION使用联合
$incomes = Income::where('user_id', Auth::User()->id);
$data = Expense::where('user_id', Auth::User()->id)->union($incomes)->paginate(10);
For manually creating a paginator, please see https://laravel.com/docs/6.x/pagination#manually-creating-a-paginator如需手动创建分页器,请参阅https://laravel.com/docs/6.x/pagination#manually-creating-a-paginator
Add the following to Income Model将以下内容添加到收入模型
protected $appends = ['type'];
public function getTypeAttribute()
{
return 'Income';
}
Add the following to Expense Model将以下内容添加到费用模型
protected $appends = ['type'];
public function getTypeAttribute()
{
return 'Expense';
}
This will add the type key in the query results.这将在查询结果中添加类型键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.