CakePHP 2的JOIN查找方法问题

时间:2019-04-19 05:36:32

标签: php mysql cakephp cakephp-2.0

  

我遇到CakePHP 查找方法和 JOIN bindModel 的问题。

     

我有2张表,分别是客户订单。   订单表包含客户的所有订单记录。

现在,在一个查询中,我需要Customer record,其中有Total到期或总订购金额。

当我尝试使用此查询时,它仅返回一条记录。

$this->Customer->bindModel(['hasOne'=>['Order'=>['fields'=>['SUM(Order.due_amount) as due']]]],false);

$data = $this->Customer->find('all',[ 'conditions' => [ 'Customer.type' => 2,'Customer.status'=>1] ]);

2nd,当我尝试使用JOIN时,仍然无法获得正确的结果

$data = $this->Customer->find('all',[
'conditions' => [ 'Customer.type' => 2,'Customer.status'=>1],
'joins' =>[[ 'table' => 'orders', 'alias' => 'Order',
'type' => 'RIGHT', /*LEFT/INNER*/
'fields'=>['SUM(Order.due_amount) as due'],
'conditions' => [ 'Order.customer_id = Customer.id']]]]);

同时使用两种方法都无法获得正确的结果

我需要这样的结果

Array( 
            [0] => Array ( [Customer] => Array ( /*all Customer table fields */ ) [Order] => Array ( [due] => 125.25))
            [1] => Array ( [Customer] => Array ( /*all Customer table fields */ ) [Order] => Array ( [due] => 10.00))
            [2] => Array ( [Customer] => Array ( /*all Customer table fields */ ) [Order] => Array ( [due] => 500.10))
.... so on 
            )

1 个答案:

答案 0 :(得分:2)

您可以使用以下查询

$joins = array(
        array('table' => 'orders',
            'alias' => 'Order',
            'type' => 'INNER',
            'conditions' => array(
                'Order.customer_id = Customer.id',
            )
        )
    );
    $conditions = [];
    $conditions[] = ['Customer.type' => 2];
    $conditions[] = ['Customer.status'=>1];
    $this->Customer->virtualFields['total_due'] = "sum(Order.due_amount)";
    $data_array = $this->Customer->find('all', ['conditions' => $conditions, 'group' => 'Customer.id', 'joins' => $joins, 'fields' => ['Customer.*', 'Customer.total_due']]);