CakePHP 3.x - ManyToMany 上的 SUM()

CakePHP 3.x - SUM() on ManyToMany

我一直坚持使用 SQL 结合关联在 CakePHP 3 中进行的函数查询。

情况如下:我有3个table,一个'products'table,一个'orders'table和一个jointable 称为 'orders_products'.

在 OrdersController 的索引中,我想将总价(= 相关产品价格的总和)添加到 table 订单中。在 SQL 中,这完全可以通过以下查询来完成:

SELECT orders.id, SUM(products.price)
FROM orders
LEFT JOIN orders_products
ON orders.id = orders_products.order_id
LEFT JOIN products
ON orders_products.product_id = products.id
GROUP BY orders.id;

我想下面的控制器代码应该可以解决问题:

$orders = $this->Orders->find('all')->contain(['Products']);

$orders
        ->select(['total_price' => $orders->func()->sum('Products.price')])
        ->group('Orders.id');

但是,当执行查询对象时,出现错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Products.price' in 'field list'

...即使定义了订单和产品之间的关联。

仅调用 $orders = $this->Orders->find('all')->contain(['Products'])->all(); return 一个订单数组,每个订单包含多个产品,必须正确设置模型。任何想法可能是错误的?提前致谢!

来自OrdersTable

$this->belongsToMany('Products', [
    'foreignKey' => 'order_id',
    'targetForeignKey' => 'product_id',
    'joinTable' => 'orders_products'
]);

来自ProductsTable

    $this->belongsToMany('Orders', [
        'foreignKey' => 'product_id',
        'targetForeignKey' => 'order_id',
        'joinTable' => 'orders_products'
    ]);

一种方法:

$orders = $this->Orders->find()
    ->select([
        'order_id' =>'orders.id',
        'price_sum' => 'SUM(products.price)'
     ])
    ->leftJoin('orders_products', 'orders.id = orders_products.order_id'),
    ->leftJoin('products', 'orders_products.product_id = products.id')
    ->group('orders.id');