如何在 Magento 2 API 中按类别过滤?

How to filter by category in Magento 2's API?

在 Magento 2 的 REST API 中,有一个选项可以使用各种搜索条件搜索产品。如您所知,下面给出了一个示例:

http://magentohost/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=name& searchCriteria[filter_groups][0][filters][0][value]=%macbook%& searchCriteria[filter_groups][0][filters][0][condition_type]=like

但是我没有找到按类别搜索的选项。

我们该怎么做?

分类搜索,很简单。您必须将 category_id 作为字段传递。看看下面的例子:

http://magentohost/rest/V1/products?searchCriteria[filterGroups][0][filters][0][field]=category_id& searchCriteria[filterGroups][0][filters][0][value]=4& searchCriteria[filterGroups][0][filters][0][conditionType]=eq&searchCriteria[sortOrders][0][field]=created_at& searchCriteria[sortOrders][0][direction]=DESC& searchCriteria[pageSize]=10& searchCriteria[currentPage]=1

您也可以同时定位多个类别:

searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=1,2,3&searchCriteria[filter_groups][0][filters][0][condition_type]=in&searchCriteria[sort_orders][0][field]=created_at&searchCriteria[sort_orders][0][direction]=DESC&searchCriteria[current_page]=1&searchCriteria[page_size]=10

我有一个小库 - https://github.com/dsheiko/magentosearchquerybuilder,可以帮助我构建此类查询

$builder = new SearchCriteria();
$builder
    ->filterGroup([
        [ "category_id", implode(",", $categories), SearchCriteria::OP_IN ],
    ])
    ->sortOrder( "created_at", "DESC")
    ->limit(1, 10);


echo $builder->toString();