CakePHP 3.x - SUM() on ManyToMany

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 07:19:04

问题


I am getting stuck on using SQL functions queries made in CakePHP 3 in combinations with associations.

The situation is as follows: I have three tables, a 'products' table, an 'orders' table and a join table called 'orders_products'.

In the index of OrdersController I would like to add the total price (= sum of relevant product prices) to the table of orders. In SQL this exactly can be done with the following query:

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;

I figured to following controller code should do the trick:

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

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

However, when the query object is executed, I get an error:

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

...Even though the association between orders and products is defined.

Calling only $orders = $this->Orders->find('all')->contain(['Products'])->all(); does return an array of orders with each order a number of products, the model has to be set up correctly. Any ideas what might be wrong? Thanks in advance!

From OrdersTable:

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

And from ProductsTable:

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

回答1:


One way to do it:

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


来源:https://stackoverflow.com/questions/38935419/cakephp-3-x-sum-on-manytomany

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!