In Magento 2, all stock items are stored in MySQL’s cataloginventory_stock_item table. You can get all the stock items easily using Resource Sample in Magento.
The following steps help you to get stock items in Magento 2:
Step 1: Employ Resource model in Magento
Step 2: Construct updated_at field
Step 3: Modernize the chosen query to find all the items has been simplified
<?php $resource = $objectManager->create('Magento\CatalogInventory\Model\ResourceModel\Stock\Item'); $select = $resource->getConnection()->select()->from($resource->getMainTable()); $stockItems = $resource->getConnection()->fetchAll($select);
In some cases, however, you need to know which stock items you need to update in certain periods like: last day, last week or last month. How can we do that?
There are some updated_at fields for organization like Magento such as Product, Order, Invoice, etc. this field records the updated time of organization. Every time it will be modified and replaced. Therefore, we can form a query which includes updated-at condition to receive all of records has be modified in a definite time.
However, there is no updated_at field in cataloginventory_stock_item updated
We have a simple solution along with updated_at field adding stock item data table and writing some commands in my setup file.
$setup->getConnection()->addColumn( $setup->getTable('cataloginventory_stock_item'), 'updated_at', \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, null, ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_UPDATE], 'Updated Time' );
Set the data type timestamp and note the attribute TIMESTAMP_UPDATE. This means that if the change in the stock item’s record means that this field will be refreshed.
<?php $resource = $objectManager->create('Magento\CatalogInventory\Model\ResourceModel\Stock\Item'); $select = $resource->getConnection()->select()->from($resource->getMainTable()); $select->where('updated_at > ?', '2018-03-19'); $stockItems = $resource->getConnection()->fetchAll($select);
Then I refresh the select query to find all the items have been updated from 03rd March 2018.