getPaginationCount()函数在Laravel的Eloquent ORM中不起作用

时间:2014-06-19 01:19:57

标签: php laravel eloquent

我拔出Eloquent模块单独使用它,但我可以访问QueryBuilder功能。除了那个之外,他们都在工作。

当我运行count()和getPaginationCount()时,count()返回正确的值,但是getPaginationCount()只返回Illuminate \ Database \ Eloquent \ Builder对象,就好像我没有命令一样要运行的查询。但是,我可以在查询日志中看到2个查询,奇怪的是,它们都运行相同的查询。

require 'vendor/autoload.php';  

use Illuminate\Database\Capsule\Manager as Capsule;  

$capsule = new Capsule;

$capsule->addConnection(array(
    'driver'    => 'mysql',
    'host'      => TECHDB_HOST,
    'database'  => TECHDB_DBNAME,
    'username'  => TECHDB_USER,
    'password'  => TECHDB_PASS,
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => ''
));

$capsule->bootEloquent();


class Indicator extends Illuminate\Database\Eloquent\Model {
    public $timestamps = false;
    public $table = "indicator_performance";
}

$query = Indicator::where('symbol', '=', 'IBM')->forPage(1,2);

var_dump($query->count()); //Correctly prints '13'

var_dump($query->getPaginationCount()); //dumps the 'Illuminate\Database\Eloquent\Builder' object

以下是查询日志:

array (size=2)
  0 => 
    array (size=3)
      'query' => string 'select count(*) as aggregate from `indicator_performance` where `symbol` = ? limit 2 offset 0' (length=93)
      'bindings' => 
        array (size=1)
          0 => string 'IBM' (length=3)
      'time' => float 4.85
  1 => 
    array (size=3)
      'query' => string 'select count(*) as aggregate from `indicator_performance` where `symbol` = ? limit 2 offset 0' (length=93)
      'bindings' => 
        array (size=1)
          0 => string 'IBM' (length=3)
      'time' => float 4.24

修改

count()调用后使用forPage()函数时,我似乎暴露了更常见的错误。看看这些结果:

$query = Indicator::where('symbol', '=', 'IBM');

var_dump($query->count()); //Correctly returns '13'
var_dump($query->forPage(0, 5)->count()); //Correctly returns '13'
var_dump($query->forPage(1, 5)->count()); //Correctly returns '13'
var_dump($query->forPage(2, 5)->count()); //Returns null. Should return '13' or '3', depending on implementation.

1 个答案:

答案 0 :(得分:1)

您的代码(和Laravel)有两个问题:

    调用Eloquent Builder的
  1. getPaginationCount()运行方法(在Query Builder类上),但不返回其结果。相反,它将自己返回为$this

  2. getPaginationCount()并未在查询中重置limitoffset以获取计数,我认为这是一个错误。只要将偏移设置为高于1的任何值,就会返回nullforPage($page)将为$page > 1执行此操作。

  3. 话虽如此,我建议您使用count()代替getPaginationCount()或:

    // first get the count
    $count = $query->getQuery()  // get the base Query Builder directly
        ->getPaginationCount();  // in order to return the count
    
    // then use forPage
    $query->forPage(1,5);