CakePHP 分组和计数

CakePHP group and count

我无法弄明白这个问题。

我有以下 3 tables: -

交易数Table

产品Table

Products_Transactions Table

所以关系是这样的 - 进行交易,然后 products_transactions table 将它们连接在一起,因为交易可以有多个产品,一个产品可以有多个交易。 join_table 还跟踪销售量,例如,一份报纸在交易 #1 中售出,数量为 2(因此售出 2 份报纸)。

现在,我想创建一个 MySQL 语句来查找在特定日期间隔内售出的所有产品,因此我得到如下信息:-

因此,它只是计算并汇总所有已售出的产品。

我已经认真地尝试了一切 - 我正在使用 CakePHP,所以其中提供的解决方案会有所帮助,但即使只是简单的 SQL 来实现这个也可能会帮助我。

到目前为止,这是我所拥有的:-

$productTransactionsTable = TableRegistry::get('products_transactions');
    $productsTransactions = $productTransactionsTable->find('all');
    $productsTransactions->matching('transactions', function ($q) {
        return $q->where([
            'transaction_date >=' => new \DateTime('-1 week'),
            'transaction_date <=' => new \DateTime('now'),
            'device_id IN' => $this->deviceIdsInDepartment(2)
        ]);
    });
    $productsTransactions->contain(['products']);

    $productsTransactions->select([
        'count' => $productsTransactions->func()->count('quantity'),
        'name' => 'products.name'
    ]);

    $productsTransactions->groupBy('products.id');

但这只会给出 1 个结果,将所有内容一起计入 1 行,如下所示:

/src/Controller/EconomyController.php (line 665)

[ (int) 0 => 对象(Cake\ORM\Entity) {

    'count' => (int) 4504,
    'name' => 'D Morgenbrød',
    '[new]' => false,
    '[accessible]' => [
        '*' => true
    ],
    '[dirty]' => [],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'products_transactions'

}

]

感谢任何帮助!我严重卡在这里了!

谢谢!

我认为您正在计算销售数量和分组的总数,因此您得到了以上结果。我认为,您需要尝试以下方法:

$data = $query
    ->select([
      'name' => 'products.name',
      'quantity' => 'products.quantity',
    ])
    ->group('products.id');