简体   繁体   English

CakePHP 2的JOIN查找方法问题

[英]Issue with CakePHP 2 find method with JOIN

I am facing an issue with CakePHP Find method with JOIN and bindModel . 我遇到带有JOINbindModel的 CakePHP Find方法的问题。

I have 2 tables, Customer and Order . 我有2个表, CustomerOrder Order table has all order records for Customer. 订单表包含客户的所有订单记录。

Now in one Query, I need Customer record with Total due or total ordered amount. 现在,在一个查询中,我需要带有Total到期或总订购金额的Customer record

When I try to use this query, It returns only one record. 当我尝试使用此查询时,它仅返回一条记录。

$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 , When i try to use JOIN , still not getting correct result 2,当我尝试使用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']]]]);

Using both method i am not getting correct result 使用两种方法我都没有得到正确的结果

I need result like this 我需要这样的结果

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 
            )

You can use below query 您可以使用以下查询

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM