Create virtual fields on the fly in CakePHP

I want to create virtual fields on the fly.

My order and order details are similar to ...

//Order Model
class Order extends AppModel {
    public $name = 'Order';
    public $actsAs = array('Containable');
    public $hasMany = array(
        'OrderDetail' => array(
            'className' => 'OrderDetail',
            'foreignKey' => 'order_id',
            'dependent' => true
        ),
    );
}

//OrderDetail Model
  class OrderDetail extends AppModel {
    public $name = 'OrderDetail';
    public $actsAs = array('Containable');
    public $belongsTo = array(
        'Order' => array(
            'className' => 'Order',
            'foreignKey' => 'order_id',
            'dependent' => true
        ),
    );
}

The model ratio is as follows. I create virtual fields on the fly to count the number of elements and their cost for pagination. I know a strange way requestAction. Is them another way of completing my task.

My verified code

        $this->Order->virtualFields['totalCost'] = 0;
        $this->Order->virtualFields['totalItem'] = 0;
        $fields = array('Order.id', 'Order.order_key', 'Order.delivery_date','COUNT(`OrderDetail`.`order_id`) AS `Order__totalItem`', 'SUM(`OrderDetail`.`cost`) AS `Order__totalCost`');         

        $this->paginate['Order'] = array("fields"=>$fields, 'conditions' => array("AND" => array($condition, "Order.status" => 3)), 'limit' => '50', 'order' => array('Order.id' => 'DESC'));

It ends with a mysql column not found for me Unknown column 'OrderDetail.order_id' in 'field list'. I did not use recursion or anchor my model to find anything else. Why does this error occur? How can I achieve my goal.

+4
source share
2 answers

" ". , :

$this->Order->virtualFields['totalCost'] = 'SUM(`OrderDetail`.`cost`)';
$this->Order->virtualFields['totalItem'] = 'COUNT(`OrderDetail`.`order_id`)';

, Order HasMany OrderDetail. CakePHP , : OrderDetail, .

?

OrderDetail Order Order.id

$fields = array
(
    'Order.id', 
    'Order.order_key', 
    'Order.delivery_date', 
    'Order.totalItem', 
    'Order.totalCost'
);         

$this->paginate['OrderDetail'] = array
(
    "fields"=> $fields, 
    'conditions' => array("AND" => array($condition, "Order.status" => 3)), 
    'limit' => '50', 
    'order' => array('Order.id' => 'DESC'),
    'group' => array('Order.id')
);
+13

" " cakephp, :

class User extends AppModel {
    public $virtualFields = array(
            'full_name' => 'CONCAT(User.first_name, " ",User.last_name)'
        ); 
}

full_name - " ", .

0

All Articles