如果在cakephp 3.0中存在多个关联,请在查询生成器中使用条件?

时间:2017-06-14 13:26:40

标签: mysql cakephp-3.0 query-builder cakephp-3.x

当我在cakephp 3.0中使用多个包含条件时,我在使用查询构建器的多级关联中遇到了麻烦。让我们假设我必须获得单个商店的数据,所以我试图添加storeId条件,但它不工作其他数据从下面的所有商店正确获取是我正在使用的查询构建器: -

// generate query               
$bestSellingReportData = $this->ArticleMaster->find('all')->contain([
    'Category' => [
        'fields' => ['Cat_Id', 'Cat_Code']
    ],
    'size_category' => [
        'fields' => ['sizeCat_Id', 'sizeCat_Code']
    ],                  
    'ItemMaster' => [
        'Invoicedetaile' => [
            'Invoice' => [
                'Store' => [
                    'fields' => ['Store_Id', 'Store_Code']
                ],
                'conditions' => ['Invoice.StoreId ='.$this->request->data['storeId']],
            ],
        ],
    ],
]);

$bestSellingReportData->select(['totalSoldItems' => $bestSellingReportData->func()->sum('Invoicedetaile.Qty')])
->matching('ItemMaster.Invoicedetaile', function ($q) {
    return $q->where([
        'AND' => [
            'Invoicedetaile.ItemId = ItemMaster.Item_ID',
        ]
    ]);
})
->group(['ArticleMaster.Article_Code'])
->order(['totalSoldItems' => 'DESC'])
->autoFields(true);

我尝试使用add condition和where子句以两种方式添加条件。但是数据不是基于条件过滤的,即storeId

1 个答案:

答案 0 :(得分:0)

在做了几个小时的R& D之后为我工作。下面是适合我的查询构建器。

   $bestSellingReportData = $this->ArticleMaster->find('all')->contain([
    'Category' => [
        'fields' => ['Cat_Id', 'Cat_Code']
    ],
    'size_category' => [
        'fields' => ['sizeCat_Id', 'sizeCat_Code']
    ],                  
    'ItemMaster' => [
        'Invoicedetaile' => [
            'Invoice',
        ],
    ],
]);

$storeId = $this->request->data['storeId'];
$bestSellingReportData->select(['totalSoldItems' => $bestSellingReportData->func()->sum('Invoicedetaile.Qty')])
->matching('ItemMaster.Invoicedetaile.Invoice', function ($q) use ($storeId) {
    return $q->where([
        'AND' => [
            'Invoicedetaile.ItemId = ItemMaster.Item_ID',
            'Invoice.StoreId ='.$storeId,
        ]
    ]);
})
->group(['ArticleMaster.Article_Code'])
->order(['totalSoldItems' => 'DESC'])
->autoFields(true);