How to get stock item list in magento 2

The following steps show you how to get stock item list in magento 2:

  1. Receiver stock item from resources model
  2. find resource model of stock item
  3. create the select query

How to get stock item list in magento 2?

  • In magento 1, you can get stock item from collection by using the following command
$stockItems = Mage::getResourceModel('cataloginventory/stock_item_collection')   ->setPageSize(10)

   ->setCurPage(1)

     ->load();
  • This command get first 10 stock item records from database, its very simple .
  • Though you cannot use this solution in magento 2 try to take a glance on the collection resources of Stock item
/vendor/magento/module-catalog-inventory/Model/ResourceModel/Stock/Item/Collection.php
/**

 * Class Collection

 * @package Magento\CatalogInventory\Model\ResourceModel\Stock\Item

 */

class Collection extends AbstractSearchResult implements StockItemCollectionInterface

{

...
  • You can see that the collection of stock item does not extend from Abstract collection. hence we cannot use the function of collection to get data such as setPageSize(), load().
  • How can we get stock item list in magento 2
  • I have an simple answer that is receiving stock item from resources model
<span style="font-weight: 400;">  </span>

$resource = $objectManager->create('Magento\CatalogInventory\Model\ResourceModel\Stock\Item');

   $select = $resource->getConnection()->select()->from($resource->getMainTable());

   $stockItems = $resource->getConnection()->fetchAll($select);
  • First, I get Resource Model of StockItem by using $objectManager. Then I create the select query using connection item. At last, I obtain data from database using $select query.

I hope the above mentioned steps help you to get stock item list in magento 2

 

Last Update: April 9, 2018  

February 3, 2018   123   Nandini R    Orders    
Total 3 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Google+
http://www.webnexs.com/blog/kb/get-stock-item-list-magento-2
Twitter
LinkedIn