我给你一个基本的想法:
$a = TableRegistry::getTableLocator()->get('a', ['table' => 'TableA']); // use your table "TableA" as alias "a"
$query = $a->find();
$result = $query->enableAutoFields(true) // select all fields
->select(['Last7DaysAmount' => $query->func()->sum('b.amount')]) // select sum('b.amount') AS Last7DaysAmount
->where(['b.date >' => DATE(NOW() - INTERVAL 7 DAY)]) // where b.date greater than current minus 7 days
->join([ // join other table
'table' => 'TableB',
'alias' => 'b',
'type' => 'left',
'conditions' => [ // with conditions
'a.client' => 'b.customer',
'a.vendor' => 'b.supplier',
'a.service' => 'b.service',
'a.country' => 'b.country',
]
])
->group([ // group results by
'a.client',
'a.vendor',
'a.service',
'a.country',
])
->order(['a.client' => 'ASC'])
->limit(100);
$this->set('results', $results);
此查询如下所示:
MariaDB [testdb]> SELECT a.id AS `a__id`, a.client AS `a__client`, a.vendor AS `a__vendor`, a.service AS `a__service`, a.country AS `a__country`, a.destination AS `a__destination`, (SUM(b.amount)) AS `Last7DaysAmount`
-> FROM tableA a
-> LEFT JOIN tableB b ON (a.client = b.customer AND a.vendor = b.supplier AND a.service = b.service AND a.country = b.country)
-> GROUP BY a.client, a.vendor, a.service, a.country
-> ORDER BY a.client
-> ASC LIMIT 100;
+-------+-----------+-----------+------------+------------+----------------+-----------------+
| a__id | a__client | a__vendor | a__service | a__country | a__destination | Last7DaysAmount |
+-------+-----------+-----------+------------+------------+----------------+-----------------+
| 1 | client1 | vendor1 | Gold | spain | spain | 106 |
| 2 | client1 | vendor3 | Gold | spain | spain | 64 |
| 3 | client2 | vendor2 | silver | germany | germany | 16 |
+-------+-----------+-----------+------------+------------+----------------+-----------------+
3 rows in set (0.001 sec)
但是,为什么 CakePHP 将 'Last7DaysAmount' 返回为 null 是另一个问题。