-2

尽管我现在使用的是 cakephp 3.8,但请帮助使用 CAKEPHP 3.X 构建查询。

我有一张桌子像:

在此处输入图像描述

还有另一个表,例如:

在此处输入图像描述

它们彼此没有关联。我不知道在 CAKEPHP 3 中开发以下结果。

SQL查询如下:

SELECT *, SUM(t2.amount) AS last7DaysAmount FROM TableA AS t1 LEFT JOIN TableB AS t2 ON t1.customer = t2.customer AND t1.supplier = t2. supplier AND t2.billing_date >= new Date('-7 Days') AND t2.country = t1.country and t2.service = t1.service

我如何使用 CakePHP 3 ORM/Query Builder LIKE So 从表 B 中获取最近 7 天选择表 A 语句的金额总和。

在此处输入图像描述

感谢您提前帮助我

4

1 回答 1

2

我给你一个基本的想法:

$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 是另一个问题。

于 2019-09-30T09:07:56.873 回答