Magento 2 How to load product collection, Category collection, Load product by id and get category by product id

I do have experience with magento 1 and in magento 1 i do know how to load the product collection, category collection, quote and product load by id.

Magento 2 is really new concept for me and syntax is completely changed in it. Need help how can i load Product collection, category collection, quote and product by id using magento 2 standard methods.

Magento 1 Product Collection:

 $productCollection = Mage::getModel('catalog/product')->getCollection();

How to call product collection in magento 2.

Magento 1 Category Collection:

$categoryCollection = Mage::getModel('catalog/category')->getCollection();

How to call category collection in magento 2

Magento 1 Load product by id :

$product = Mage::getModel('catalog/product')->load($id);

How to load in magento 2

Magento 1 load category by product id:

    $product = Mage::getModel('catalog/product')->load($_item['product_id']);
    $cats = $product->getCategoryIds();

How to load in magento 2?

Solutions

Magento 2 Product Collection:

In magento2, for getting product collection at any class,You should inject Factory class Magento\Catalog\Model\ResourceModel\Product\CollectionFactory in __construction function.

namespace [YourClassNameSpace];
class [YourClassName]
{
protected $_productCollectionFactory;
 public function __construct(
    ....
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    .....
    ) {
    .....
        $this->_productCollectionFactory = $productCollectionFactory;
    .....
 }

public function getProductCollection(){

    $collection = $this->_productCollectionFactory->create();
    /* Addtional */
    $collection
        ->addMinimalPrice() // add for Minimal
        ->addFinalPrice()  // add for Final Price 
        ->addTaxPercents() // add for Tax
        ->addAttributeToSelect('*') // use * for all product  attribute
        ->addUrlRewrite(); // Add for Url   
    return $collection;
}

}

Category collection:

For getting categry collection at any class,You should inject Factory class Magento\Catalog\Model\ResourceModel\Category\CollectionFactory in __construction function

namespace [YourClassNameSpace];
class [YourClassName]
{
    protected $_CategoryCollectionFactory;
     public function __construct(
        ....
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $CategoryCollectionFactory,
        .....
        ) {
        .....
        $this->_CategoryCollectionFactory = $CategoryCollectionFactory;
        .....
     }

    public function getCategoryCollection(){

        $collection = $this->_CategoryCollectionFactory->create();
        /* Addtional */
        $collection
            ->addAttributeToSelect('*') // use * for all Category  attribute
            ->joinUrlRewrite(); // Joins url rewrite rules to collection
        return $collection;
    }
}

CALL PRODUCT COLLECTION

You need to define dependency as below

public function __construct(    
    ....
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    ...
)
{    
    $this->_productCollectionFactory = $productCollectionFactory;
}

 public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    return $collection;
}

For Category collection

   protected $_categoryCollection;

   public function __construct(
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollection       
    ) {
        $this->_categoryCollection = $categoryCollection;
    }      

    public function getCategoryCollection()
    {
        $collection = $this->_categoryCollection->create()
            ->addAttributeToSelect('*');

        return $collection;
    }

Product Get By ID

  protected $productRepository; 
  protected $_storeManager; 

  public function __construct(
    ProductRepositoryInterface $productRepository
  ) {
      $this->productRepository = $productRepository;
  }
  public function getProduct()
  {

      $productId=1;
      return $product = $this->productRepository->getById($productId);
  }

You can also do same for load category by product id.

Category By product ID

protected $_categoryFactory
protected $_productFactory

public function __construct(    
    ....
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Catalog\Model\ResourceModel\CategoryFactory $categoryFactory 
    ...
){
    $this->_categoryFactory = $categoryFactory;
    $this->_productFactory = $productFactory;

}

public function getCategoryFromProductId(){
    $product = $this->_productFactory->create()->load($pid);
    $cats = $product->getCategoryIds(); //array
    if(count($cats) ){
        $firstCategoryId = $cats[0];
        $_category = $this->_categoryFactory->create()->load($firstCategoryId);
        return $_category->getName();
    }
}

Similar questions

How to load an external file to load and execute our custom JS files on the Magento site?
seeking some advises. My Magento-2 project has 2 custom JS files that I would like replicated and loaded externally on the site. This arrangement is for our client to use them to add his own code changes and deploy them directly to the production server whenever he makes minor changes in these JS files. Just to give you an example, he wants to chan...
What is the equivalent of the config node category/collection/attributes in Magento 2 to add an attribute to the category collection
I am porting a Magento 1 module, which adds a custom category attribute, to Magento 2. The product is already created in Magento 2 - but now it does not appear in the inside \Magento\Catalog\Helper\Category::getCategoryUrl. In the Magento 1 version config.xml I had: This solved the problem. What is the equivalent of this in Magento 2 ? Sure, I coul...
buy a product from X category and buy a product from Y category and get 15% off on total price of two products , How to setup this?
buy a product from X category and buy a product from Y category and get 15% off on the total price of two products, How to set up this? 15% should apply only to the total price of two products, not on the entire cart. Please guide.
Magento get all product attribute from report collection without load
I used this product collection but when I use foreach for this collection I can not fetch all product attributes like(small_image).I know one solution in foreach $product=Mage::getModel('catalog/product')->load($_product->getId()); But I do not want to use load in foreach loop. Any alternative soltution ?
Magento 2.3 product collection->getData get correct answer but foreach or load() not
Same with here : Magento 1: $productCollection->getData() vs foreach ($productCollection as $product), want add more information. Create new product then Now And try Both method return null, Why I can't get the item after load() or using foreach function?
Magento 2 - How to get category name and category tree for product or for category id?
Magento 2.2.7 I have to output category name and "tree" or path for product. For instance if my product is in category Lg775 my output should be: Hardware/Motherboards/Intel/Lg775 so far I have this code that gives me category ID: Thank you all Magento experts for all the help so far! I really appreciate it :) So I used the answer I checked however...

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy.