3

I am creating custom rest API for getting all products including out of stock products too but I am not able to get out of stock products.

/**
 * Get products with filter.
 * 
 * @param string $fieldName
 * @param string $fieldValue
 * @param string $filterType
 * @return \Magento\Catalog\Api\Data\ProductInterface[]
 */
public function getFeedarmy(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria) {
    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $storesCollection = $this->_storeManager->getStores();
    $storeIds = [];
    foreach ($storesCollection as $sc) {
        $storeIds[] = $sc['store_id'];
    }

    $items = [];
    $productCollection = $this->collectionFactory->create();

    $productCollection->setFlag('has_stock_status_filter', false);
    $productCollection->setFlag('require_stock_items', false);

    //$productCollection->setSkipSaleableCheck(true);

    $productCollection->addAttributeToSelect('*')
            ->setStoreId($storeIds)
            //->joinField( 'manage_stock', 'cataloginventory_stock_item', 'manage_stock', 'product_id=entity_id', null, 'left' )
            //->addMinimalPrice()
            ->addCategoryIds()
            //->addTierPriceData()
            ->addPriceData()
            //->addMediaGalleryData()
            ->joinField('inventory_in_stock', 'cataloginventory_stock_item', '*', 'product_ids=entity_id', 'qty>=0', 'left')
            //->addAttributeToFilter('is_in_stock', array('in' => ['0','1']))
            ->addTaxPercents();

    $this->collectionModifier->apply($productCollection);

    foreach ($searchCriteria->getFilterGroups() as $filterGroups) {
        foreach ($filterGroups->getFilters() as $filter) {
            $productCollection->addAttributeToFilter($filter->getField(), [$filter->getConditionType() => $filter->getValue()]);
        }
    }

    if (is_array($searchCriteria->getSortOrders()) && count($searchCriteria->getSortOrders())) {
        foreach ($searchCriteria->getSortOrders() as $sortOrder) {
            $productCollection->addOrder($sortOrder->getField(), $sortOrder->getDirection() == \Magento\Framework\Api\SortOrder::SORT_ASC ? 'ASC' : 'DESC');
        }
    }

    $productCollection->setPageSize($searchCriteria->getPageSize());
    $productCollection->setCurPage($searchCriteria->getCurrentPage());

    foreach ($productCollection as $item) {

        $customOptions = $_objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($item);
        $data = $item->getData();

        $productCustomOptions = [];
        foreach ($customOptions as $k => $co) {
            $coData = $co->getData();
            $optionValues = [];
            foreach ($co->getValues() as $cov) {
                $optionValues[] = $cov->getData();
            }
            $productCustomOptions[] = array(
                'option_id' => $coData['option_id'],
                'product_id' => $coData['product_id'],
                'type' => $coData['type'],
                'is_require' => $coData['is_require'],
                'sku' => $coData['sku'],
                'max_characters' => $coData['max_characters'],
                'file_extension' => $coData['file_extension'],
                'image_size_x' => $coData['image_size_x'],
                'image_size_y' => $coData['image_size_y'],
                'sort_order' => $coData['sort_order'],
                'default_title' => $coData['default_title'],
                'store_title' => $coData['store_title'],
                'title' => $coData['title'],
                'default_price' => $coData['default_price'],
                'default_price_type' => $coData['default_price_type'],
                'store_price' => $coData['store_price'],
                'store_price_type' => $coData['store_price_type'],
                'price' => $coData['price'],
                'price_type' => $coData['price_type'],
                'values' => $optionValues,
            );
        }

        $items[$item->getId()] = array(
            'id' => $item->getId(),
            'sku' => $data['sku'],
            'name' => $item->getName(),
            'url_key' => $item->getUrlKey(),
            'attribute_set_id' => $item->getAttributeSetId(),
            'store_ids' => $item->getStoreIds(),
            'parent_ids' => $this->_catalogProductTypeConfigurable->getParentIdsByChild($item->getId()),
            'price' => $data['price'],
            'status' => $data['status'],
            'visibility' => $data['visibility'],
            'type_id' => $data['type_id'],
            'created_at' => $data['created_at'],
            'updated_at' => $data['updated_at'],
            'weight' => $data['weight'],
            'weight_unit' => $this->getWeightUnit(),
            'product_links' => $item->getProductLinks(),
            'tier_prices' => $item->getTierPrices(),
            'custom_attributes' => array(
                array(
                    'attribute_code' => 'description',
                    'value' => $item->getDescription()
                ),
                array(
                    'attribute_code' => 'image',
                    'value' => $item->getImage()
                ),
                array(
                    'attribute_code' => 'small_image',
                    'value' => $item->getSmallImage()
                ),
                array(
                    'attribute_code' => 'thumbnail',
                    'value' => $item->getThumbnail()
                ),
                array(
                    'attribute_code' => 'color',
                    'value' => $item->getColor()
                ),
                array(
                    'attribute_code' => 'category_ids',
                    'value' => $item->getCategoryIds()
                ),
            ),
            'stock_information' => array(
                'item_id' => $data['item_id'],
                'product_id' => $data['product_id'],
                'stock_id' => $data['stock_id'],
                'qty' => $data['qty'],
                'is_in_stock' => $data['is_in_stock'],
                'is_qty_decimal' => $data['is_qty_decimal'],
                'use_config_min_qty' => $data['use_config_min_qty'],
                'min_qty' => $data['min_qty'],
                'use_config_min_sale_qty' => $data['use_config_min_sale_qty'],
                'min_sale_qty' => $data['min_sale_qty'],
                'use_config_max_sale_qty' => $data['use_config_max_sale_qty'],
                'max_sale_qty' => $data['max_sale_qty'],
                'use_config_backorders' => $data['use_config_backorders'],
                'backorders' => $data['backorders'],
                'use_config_notify_stock_qty' => $data['use_config_notify_stock_qty'],
                'notify_stock_qty' => $data['notify_stock_qty'],
                'use_config_qty_increments' => $data['use_config_qty_increments'],
                'qty_increments' => $data['qty_increments'],
                'use_config_enable_qty_inc' => $data['use_config_enable_qty_inc'],
                'enable_qty_increments' => $data['enable_qty_increments'],
                'use_config_manage_stock' => $data['use_config_manage_stock'],
                'manage_stock' => $data['manage_stock'],
                'low_stock_date' => $data['low_stock_date'],
                'is_decimal_divided' => $data['is_decimal_divided'],
                'stock_status_changed_auto' => $data['stock_status_changed_auto'],
            ),
            'custom_options' => $productCustomOptions,
        );

        //$items[$item->getId()] = $item;
    }

    $searchResult = $this->searchResultFactory->create();

    $searchResult->setItems($items);


    $searchResult->setTotalCount(count($items));
    $searchResult->setSearchCriteria($searchCriteria);

    return $searchResult;
}

I tried to identify the reason and found that the query for getting the product has joined with kdmcatalog_product_entity and kdmcatalog_product_index_price, where if the product is out of stock removed from the kdmcatalog_product_index_price table so the join does not return the out of stock of products

SELECT `e`.*, `price_index`.`price`, `price_index`.`tax_class_id`, `price_index`.`final_price`, IF(price_index.tier_price IS NOT NULL, LEAST(price_index.min_price, price_index.tier_price), price_index.min_price) 
AS `minimal_price`, `price_index`.`min_price`, `price_index`.`max_price`, `price_index`.`tier_price`, `at_inventory_in_stock`.* 
FROM `kdmcatalog_product_entity` AS `e` INNER JOIN
`kdmcatalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0 
LEFT JOIN `kdmcataloginventory_stock_item` 
AS `at_inventory_in_stock` ON (at_inventory_in_stock.`product_id`=e.entity_id) AND (qty>=0) 
WHERE (`e`.`sku` = 'ab,Nike Air Max Dia SE-us 5.5')
1
  • Have you got solution for get product with stock information in rest API. I am facing for same issue. Commented Aug 27, 2019 at 12:04

1 Answer 1

0

this module will solve your issue, it will return the stockinfo in searchCriteria. https://github.com/menacoders/Stock-Info-API-searchCriteria

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.