簡體   English   中英

getPaginationCount()函數在Laravel的雄辯ORM中不起作用

[英]getPaginationCount() function not working in Laravel's Eloquent ORM

我將退出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

編輯:

似乎在forPage()調用之后使用count()函數暴露了一個更一般的錯誤。 看一下這些結果:

$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.

您的代碼(和Laravel)有兩個問題:

  1. getPaginationCount() Builder上調用的getPaginationCount()運行方法(在Query Builder類上),但不返回其結果。 相反,它將自身返回為$this

  2. getPaginationCount()不會重置查詢的limitoffset以獲得計數,我想這是一個錯誤。 每當將offset設置為大於1的任何null時,這都會導致返回forPage($page)將對$page > 1

話雖如此,我建議您要么使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM