使用CakePHP分页对计算字段进行排序

时间:2014-05-23 12:25:18

标签: cakephp pagination

我试图获取分页结果列表,但我希望选择在计算字段上对它们进行排序。

我有这个:

$this->Paginator->settings = array(
        'fields' => 'COUNT(Invoice.id) as totalInvoices,
                 SUM(Invoice.price_paid) as totalPaid,
                 MAX(Invoice.invoice_date) as latestInvoice',
        'group' => array('Invoice.supplier_id'),
        'order' => array($order => $direction)
    );

$ order是要排序的字段的名称,$ direction只是' asc'或者' desc'。

如果我对数据库中存在的字段进行排序,例如' price_paid'按照每个用户的数量或其他数量来查找发票,但它似乎无法应对totalPaid或latestInvoice上的排序 - 我只是得到了未排序的结果。

我尝试创建一个虚拟字段,例如

$this->Invoice->virtualFields['latestInvoice'] = 'MAX(Invoice.invoice_date)';
$order = "Invoice.latestInvoice";

但这似乎没有任何区别 - 排序顺序仍然被忽略。

我在网上寻找解决方案,但他们似乎都是通过使用虚拟字段来解决问题,这对我来说显然无效!

1 个答案:

答案 0 :(得分:5)

我尝试使用虚拟字段,它对我来说工作正常,下面是我的代码可能有用: -

$this->Invoice->virtualFields['latestInvoice'] = 'MAX(Invoice.invoice_date)';
$order = "Invoice.latestInvoice";
$options = array(               
                'fields' => 'COUNT(Invoice.id) as totalInvoices,
                      SUM(Invoice.price_paid) as totalPaid,
                      MAX(Invoice.invoice_date) as latestInvoice',
                'order' => array($order =>'asc'),
            );
$this->paginate = $options;
$list = $this->paginate('Invoice');
pr($list);die;

同时检查数组中虚拟字段是否在$ list中。