douhui4699 2013-08-19 20:34
浏览 24
已采纳

基于模型方法的Cakephp分页

In my Order model I have the following method to sum the total price of the Order's OrderItems

public function getTotalPrice($id = null) {
    if (!$this->exists($id)) {
        throw new NotFoundException(__('Invalid order'));
    }
    $total = $this->OrderItem->find('first', array(
        'conditions' => 'OrderItem.order_id = '.$id,
        'fields' => 'SUM('.$this->OrderItem->virtualFields['total_price'].') AS total',
        'group' => 'OrderItem.order_id'

    ));
    return $total[0]['total'];
}

In my OrderController's view action I am calling this method and the setting the value to send to the view.

In my Order's index view I see Paginator links like this for the baked fields.

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

But as I understand it, the parameter to sort needs to be an actual field on the model. Is there any way to use this Paginator helper to paginate with my custom method? Or is there a way to make my method be used as a virtual field on my Order model?

Update I added the following custom find method on my Order model

public $findMethods = array('withTotal' =>  true);

protected function _findWithTotal($state, $query, $results = array()) {
    if ($state === 'before') {
        // make sure to fetch OrderItems
        if(!isset($query['contain'])) {
            $query['contain'] = 'OrderItem';
        } else if (is_array($query['contain'])) {
            if(!in_array('OrderItem', $query['contain'])) {
                array_push($query['contain'], 'OrderItem');
            }
        } else if(is_string($query['contain']) && strpos($query['contain'], 'OrderItem') === false) {
            $query['contain'] = array($query['contain'], 'OrderItem');
        }
        return $query;
    } else if ($state === 'after') {
        if(count($results) > 0) {
            foreach($results as &$order) {
                if(isset($order['OrderItem'])) {
                    $total = 0;
                    foreach($order['OrderItem'] as $orderItem) {
                        $total += $orderItem['total_price'];
                    }
                    $order['Order']['order_total'] = $total;
                }
            }
        }
    }
    return $results;
}

then I added the following to the Order's index view

$this->paginate = array(
    'findType' => 'withTotal'
);

before calling $this->paginate('Order'). Now I am able to read the value of $order['Order']['order_total'] in my view but when I click the $this->Paginator->sort('order_total') link it updates the parameter in the url but does not sort the rows.

Update 2 with SOLUTION

To fix the sorting problem I implemented the following paginate method in my Order controller

public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
    // get orders with total
    $contain = $extra['contain'];
    $orders = $this->find('withTotal', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive', 'group', 'contain'));
    // if sorting by order_total
    if(is_array($order) && array_key_exists('order_total', $order)) {
        $sortDirection = $order['order_total'];
        uasort($orders, function($a, $b) use($sortDirection) {
            if($a['Order']['order_total'] == $b['Order']['order_total']) {
                return 0;
            } else if($sortDirection == "asc") {
                return ($a['Order']['order_total'] > $b['Order']['order_total']) ? -1 : 1;
            } else if($sortDirection == "desc") {
                return ($a['Order']['order_total'] < $b['Order']['order_total']) ? -1 : 1;
            }
        });
    }
    return $orders;
}

I also had to add an empty virtual field named order_total to get the pagination sort validation to pass

public $virtualFields = array( 
    'order_total' => '\'\''
);
  • 写回答

1条回答 默认 最新

  • dongxi9326 2013-08-19 22:15
    关注

    Read this. First key of the array is the find method.

    public $paginate = array(
        'popular'
    );
    

    Since the 0th index is difficult to manage, in 2.3 the findType option was added:

    public $paginate = array(
        'findType' => 'popular'
    );
    

    Also instead of paginate you should use $this->Paginator->settings in 2.3, looks like the book example is not up to date yet.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?