我有这段代码,我想对 $shares 进行分页。
如何存档?
$level = Share::join('follows', 'shares.user_id', '=', 'follows.user_id')
->where('follows.follower_id', Auth::user()->id)
->where('follows.level', 1)
->get(array('shares.*'));
//get 10% of shares
$count = Share::count()/10;
$count = round($count);
$top10 = Share::orderBy('positive', 'DESC')
->take($count)
->get();
$shares = $top10->merge($level);
//get only unique from shares
$unique = array();
$uniqueShares = $shares->filter(function($item) use (&$unique) {
if (!in_array($item->id, $unique)) {
$unique[] = $item->id;
return true;
} else {
return false;
}
});
//order by id
$shares = $uniqueShares->sortBy(function($share)
{
return -($share->id);
});
return View::make('layout/main')
->with('shares', $shares);
最佳答案
这里有很多多余的不必要的代码。
第一:
$level = Share::join('follows', 'shares.user_id', '=', 'follows.user_id')
->where('follows.follower_id', Auth::user()->id)
->where('follows.level', 1)
->get(array('shares.*'));
为什么您要获取所有记录,然后再将其丢弃?
第二:
$shares = $top10->merge($level);
为什么要合并两个数组?
第三:
$uniqueShares = $shares->filter(function($item) use (&$unique) {
if (!in_array($item->id, $unique)) {
$unique[] = $item->id;
return true;
} else {
return false;
}
});
您必须编写此代码片段,因为在上面的第二中,您合并了两个数组,这将产生重复的条目。那么为什么要合并?
第四:
//order by id
$shares = $uniqueShares->sortBy(function($share)
{
return -($share->id);
});
这就是您真正想要的实际数据。
让我们回顾一下
你需要
- 总股本的 10%
- 按某些
正数
列排序 - 也许正如我猜测的那样,按股票数量排序。
要使用内置的paginate()
,您需要paginate()
,这是必须的。
休息很简单。
- 计算总结果。
round(Share::count()/10)
- 将其作为第一个参数放入
paginate()
中。 - 根据需要添加 order by 子句。
- 查看代码,您似乎不会/不应该添加可能添加了
distinct
和group by
子句的重复数据。
在 Share::count()/10;
中使用 remember
来缓存它。您不需要一遍又一遍地运行查询。
你就完成了。
关于mysql - Laravel - 如何在这里分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18413197/