【问题标题】:CakePHP 3 - pagination - how to sort calculated field?CakePHP 3 - 分页 - 如何对计算字段进行排序?
【发布时间】:2016-11-19 13:17:52
【问题描述】:

对不起我的英语,但我希望你能理解我。

数据库中不存在字段availability。它随后在formatResults 中创建。结果显示正确,但无法按availability 字段排序。

我试过这种方法,但它不起作用:

$query = $this
    ->WebshopProducts
    ->find('all')
    ->
    ->formatResults(function($results) {
        return $results->map(function($row) {
            if($row->stock_total - $row->stock_min > 0){
                $row->availability='Yes';
            }else{
                $row->availability='No';
            }
            return $row;
        });
    });

【问题讨论】:

  • $this->paginate = [ 'sortWhitelist'=>['availability']];

标签: sorting cakephp pagination calculated-columns cakephp-3.x


【解决方案1】:

我找到了解决方案。这可能对某人有帮助:

$query = $this->WebshopProducts->find('all');
            $availabilityCase = $query->newExpr()->addCase(
            [$query->newExpr()->add(['(stock_total - stock_min) >' => 0]),$query->newExpr()->add(['(stock_total - stock_min) <=' => 0])],['YES','NO'],['string','string']);
            $query->select(['id','active','title','price','stock_total','position','availability' => $availabilityCase]);        
        $this->set('webshopProducts', $this->paginate($query));

【讨论】:

    【解决方案2】:
    $query = $this
    ->WebshopProducts
    ->find('all')
    ->select('Availibility'=>'(WebshopProducts.stock_total - WebshopProducts.stock_min)', **(Other required fields)**)
    ->order('Availibility'=>"DESC")
    ->formatResults(function($results) {
        return $results->map(function($row) {
            if($row->stock_total - $row->stock_min > 0){
                $row->availability='Yes';
            }else{
                $row->availability='No';
            }
            return $row;
        });
    });
    

    在你的视图文件中应该是

    <th><?php echo $this->Paginator->sort('Availibility'); ?></th>
    

    我不确定,但你可以试试这个。

    【讨论】:

    • 感谢 Haresh 提供的良好解决方案。我以不同的方式解决了这个问题。我的解决方案如下
    猜你喜欢
    • 2014-07-12
    • 2011-08-26
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 2016-05-15
    相关资源
    最近更新 更多