1

I want to get products By Id but it the way i am doing this doesnot return some product details in case of configurable

<?php


namespace Vendor\MobileApp\Model\Api;

use Vendor\MobileApp\Api\ProductInterface;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductsCollectionFactory;
use Vendor\MobileApp\Helper\Data as ApiHelper;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory as BestSellersCollectionFactory;
use Magento\Reports\Model\ResourceModel\Product\CollectionFactory as MostViewedCollectionFactory;
use Magento\Framework\Webapi\Rest\Request as ApiRequest;
use Magento\Framework\Escaper;

/**
*  Store Details Provider
*/

class ProductRepository implements ProductInterface {

    /**
    * @var ProductsCollectionFactory
    */
    protected $collectionFactory;

    /**
    * @var BestSellersCollectionFactory
    */
    protected $_bestSellersCollectionFactory;

    /**
    * @var BestSellersCollectionFactory
    */
    protected $_mostViewedProductFactory;

    /**
     * @var CategoryFactory
     */
    protected $categoryFactory;

    /**
    * @var ApiRequest
    */
    protected $request;

    /**
    * @var Escaper
    */
    protected $escaper;

    /**
    *  Constructor VirtualProductInformation Class
    *
    *   @param ProductsCollectionFactory $collectionFactory,
    *   @param BestSellersCollectionFactory $bestSellersCollectionFactory,
    *   @param MostViewedCollectionFactory $mostViewedProductFactory,
    *   @param CategoryFactory $categoryFactory,
    *   @param ApiRequest $request,
    *   @param Escaper $escaper
    *   @param ApiHelper $apiHelper
    *
    */

    public function __construct(
        ProductsCollectionFactory $collectionFactory,
        BestSellersCollectionFactory $bestSellersCollectionFactory,
        MostViewedCollectionFactory $mostViewedProductFactory,
        CategoryFactory $categoryFactory,
        ApiRequest $request,
        Escaper $escaper,
        ApiHelper $apiHelper
    ) {
        $this->collectionFactory = $collectionFactory;
        $this->_bestSellersCollectionFactory = $bestSellersCollectionFactory;
        $this->_mostViewedProductFactory = $mostViewedProductFactory;
        $this->categoryFactory = $categoryFactory;
        $this->request = $request;
        $this->escaper = $escaper;
        $this->apiHelper = $apiHelper;
    }



    /**
    * Get Products By Category
    *
    * @api
    * @param int $categoryId
    * @param int $pageSize
    * @param string $storeCode
    *
    * @return array
    */
    public function getProductsByCategory( $categoryId, $pageSize, $storeCode ) {

        // Return If Module is Disabled
        if ( 0 === $this->apiHelper->getModuleStatus() ) {
            $response[ 0 ][ 'success' ] = 0;
            $response[ 0 ][ 'message' ] = $this->apiHelper->translateMessage( 'Setting Api is disabled', $storeCode );
            return $response;
        }

        $storeId = $this->apiHelper->getStoreByCode( $this->escaper->escapeHtml( $storeCode ) );
        $categoryId = $this->escaper->escapeHtml( $categoryId );
        $productPerPage = $this->escaper->escapeHtml( $pageSize );

        $category = $this->categoryFactory->create()->load($categoryId);
        $category->setStoreId($storeId); 
        if($category) {
            $productCollection = $category->getProductCollection();
            $productCollection->setPagesize($productPerPage);

            echo "<pre>"; print_r($productCollection); exit;
            $response[0]['success'] = 1;
            $response[ 0 ][ 'data' ] = $this->getProductData( $productCollection );
        } else {
            $response[0]['success'] = 0;
            $response[ 0 ][ 'message' ] = $this->apiHelper->translateMessage("The Category with given Id doesnot exist", $storeCode);
        }

        return $response;
    }
    

    /**
    * Get product data including image URLs.
    *
    * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $products
    * @return array
    */
    protected function getProductData( $products ) {
        $data = [];
        foreach ( $products as $product ) {
            $productData = $product->getData();
            $productData[ 'image_url' ] = $this->getProductImageUrl( $product );
            $data[] = $productData;
        }
        return $data;
    }


    /**
    * Get product image URL.
    *
    * @param \Magento\Catalog\Model\Product $product
    * @return string|null
    */
    protected function getProductImageUrl( $product ) {
        $image = $product->getImage();
        if ( $image && $image != 'no_selection' ) {
            $mediaUrl = $this->apiHelper->getMediaUrl();
            return $mediaUrl . 'catalog/product' . $image;
        }
        return null;
    }
}

1 Answer 1

1

Try this all steps

1.Step 1: Inject the necessary dependencies Inject the following dependencies into your ProductRepository class constructor:

use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\FilterGroupBuilder;

protected $productRepository;
protected $searchCriteriaBuilder;
protected $filterBuilder;
protected $filterGroupBuilder;

public function __construct(
    ProductRepository $productRepository,
    SearchCriteriaBuilder $searchCriteriaBuilder,
    FilterBuilder $filterBuilder,
    FilterGroupBuilder $filterGroupBuilder
) {
    $this->productRepository = $productRepository;
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->filterBuilder = $filterBuilder;
    $this->filterGroupBuilder = $filterGroupBuilder;
}

2.Retrieve products by ID Add the following method to your ProductRepository class:

 public function getProductsByIds(array $productIds)
 {
    $filter = $this->filterBuilder
        ->setField('entity_id')
        ->setConditionType('in')
        ->setValue($productIds)
        ->create();

    $filterGroup = $this->filterGroupBuilder
        ->addFilter($filter)
        ->create();

    $searchCriteria = $this->searchCriteriaBuilder
        ->setFilterGroups([$filterGroup])
        ->create();

    $products = $this->productRepository->getList($searchCriteria)->getItems();

    return $products;
 }

3.Usage example You can now use the getProductsByIds method to retrieve products by their IDs. Here's an example of how to use it in your code.

  $productIds = [1, 2, 3]; // Replace with your desired product IDs
  $products = $this->getProductsByIds($productIds);

  foreach ($products as $product) {
    // Access the product details
    $productId = $product->getId();
    $productName = $product->getName();
    // ... and other product attributes
  }

NOTE: That's it! By following these steps

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.