CakePHP 3 - 分页 - 如何对计算字段进行排序?

时间:2016-07-16 12:27:22

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

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

数据库中不存在字段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;
        });
    });

2 个答案:

答案 0 :(得分:0)

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

我不确定,但你可以尝试一下。

答案 1 :(得分:0)

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

$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));