如何通过API的相关数据过滤大量表格?

时间:2015-06-09 13:24:20

标签: cakephp-3.0

方案
我正在构建一个API端点,我需要通过某个字段过滤查询中的所有数据。在这种情况下,可以使用site_id请求端点,该Sites应按传递的值过滤所有表和相关表。

设置
我包含大量的表类,并且如果它们与// src/Model/Table/PackagesTable.php $this->addBehavior('ApiVerbose', [ 'contain' => [ 'Broadbands' => [ 'Hubs', 'BroadbandTypes', 'Attributes' => [ 'AttributeTypes', 'Sites' ], 'conditions' => [ 'Broadbands.status_id' => 1, 'Broadbands.deleted' => false ] ], 'Calls' => [ 'Attributes' => [ 'AttributeTypes', 'Sites' ], 'conditions' => [ 'Calls.status_id' => 1, 'Calls.deleted' => false ] ], 'Tvs' => [ 'Attributes' => [ 'AttributeTypes', 'Sites' ], 'conditions' => [ 'Tvs.status_id' => 1, 'Tvs.deleted' => false ] ], 'Boxes' => [ 'conditions' => [ 'Boxes.status_id' => 1, 'Boxes.deleted' => false ] ], 'LineRentals' => [ 'conditions' => [ 'LineRentals.status_id' => 1, 'LineRentals.deleted' => false ] ], 'Providers' => [ 'conditions' => [ 'Providers.status_id' => 1, 'Providers.deleted' => false ] ], 'SamknowsProviders', 'PackageTypes' => [ 'conditions' => [ 'PackageTypes.status_id' => 1, 'PackageTypes.deleted' => false ] ], 'Pricings' => [ 'Expiries', 'conditions' => [ 'Pricings.status_id' => 1, 'Pricings.deleted' => false ] ], 'PriceTypes', 'Offers' => [ 'OfferTypes', 'Expiries', 'Sites', 'conditions' => [ 'Offers.status_id' => 1, 'Offers.deleted' => false ] ], 'Attributes' => [ 'AttributeTypes', 'Expiries', 'Sites', 'conditions' => [ 'Attributes.status_id' => 1, 'Attributes.deleted' => false ] ], 'Sites' ] ]);

相关,则会过滤每个类。
site_id

预期行为
我不希望返回任何与传递的Broadbands.Attributes无关的包,而且我希望它们的相关表格如site_id将被传递的{{1}过滤掉}}

我目前有什么

/**
 * Filter the result set by site id
 *
 * @param Query $query
 * @return Query
 */
protected function filterBySite(Query $query)
{
    if (!isset($this->_controller()->request->query['verbose'])) {
        return $query;
    }

    $siteId = $this->_controller()->request->query['site_id'];

    // TODO: Need to figure out how to filter the data without using matching() as it puts the matched data into the _matchingData array
    if(in_array('sites', $this->_table()->associations()->keys())) {
        $query->contain('Sites')
            ->matching('Sites', function ($q) use ($siteId) {
                return $q->where(['Sites.id' => $siteId]);
            });
    }

    if (in_array('attributes', $this->_table()->associations()->keys())) {
        $query->matching('Attributes', function ($q) use ($siteId) {
            return $q->where(['Sites.id' => $siteId]);
        });
    }

    return $query;
}

为什么我要避免matching()
我发现使用matching()将匹配数据放入_matchingData数组元素,这意味着我需要在查询中的所有表上使用matching(),然后分配{ {1}}到视图,以便可以为响应序列化。

最佳方法?
所以我对如何解决这类问题很感兴趣。如何在这多个表类中一致地过滤这么多数据,并且仍然返回准确的分页数组以及正确的过滤数据,而不是用户不需要的其他数据数据。

0 个答案:

没有答案