简体   繁体   中英

Magento 2 REST API filter by category

In magento 2 REST API, there is an option to search a product using various search criteria. As you know, an example is given below

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

But I have not found an option to search by category. How can we do that.?

To search by category, it is simple. You have to just pass category_id as a field. Have a look at below example:

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

You can also target multiple categories at once:

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

I have a little lib - https://github.com/dsheiko/magentosearchquerybuilder , which helps me building such queries

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


echo $builder->toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM