mysql - Laravel - 如何在这里分页?

标签 mysql sql pagination laravel laravel-4

我有这段代码,我想对 $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(),这是必须的。

休息很简单。

  1. 计算总结果。 round(Share::count()/10)
  2. 将其作为第一个参数放入 paginate() 中。
  3. 根据需要添加 order by 子句。
  4. 查看代码,您似乎不会/不应该添加可能添加了 distinctgroup by 子句的重复数据。

Share::count()/10; 中使用 remember 来缓存它。您不需要一遍又一遍地运行查询。

你就完成了。

关于mysql - Laravel - 如何在这里分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18413197/

相关文章:

php - PHP 中的 Mysql 空查询 - 我得到了什么?资源编号?

sql - 一个 SQLite 查询中的两个总和和三个表

jquery - 检测 DataTable 上的页面更改

mysql - 使用 DMS 复制数据库时出错

php 在 mysql 中使用单列数组

php - MySQL搜索名字和姓氏

sql - 从 SQL Server 表为直方图创建范围箱

mysql - 我登录了 phpmyadmin。登录后我收到错误。

jquery - 如何使用 jQuery DataTables 发布整个表的数据

ruby-on-rails - 带分页功能的 Google 自定义搜索 API