0

I am trying to use the itemFactory to get last 30 minutes (updated_at) data from sales_order_item table , but not success. Anyone can hep to verify where I did wrong?

use Magento\Sales\Model\Order\ItemFactory as itemFactoryCollection;



   protected $itemFactory;



  public function __construct(
        itemFactoryCollection $itemFactory
    ) {
        $this->itemFactory = $itemFactory;
    }


public function getOrderItems(): itemFactory
    {
        $orderItemCollectData = $this->itemFactory->create()->getCollection();
    
         $orderItemCollectData->getSelect()
          ->where(
                'updated_at >= ?',
                $orderItemCollectData->getConnection()->getDateSubSql(
                    new Zend_Db_Expr('NOW()'),
                    '30',
                    AdapterInterface::INTERVAL_MINUTE
                )
            );
        return $orderItemCollectData;
    }

$OrderItems = $this->getOrderItems();

1 Answer 1

1

I like to use a CollectionFactory to create the collection, then use the pre-baked methods for querying.

Try injecting these :

\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory $itemCollectionFactory,
\Magento\Framework\Stdlib\DateTime\DateTime $dateTime

Then use it like this:

// 'Y-m-d H:i:s' is the MySQL timestamp format
$timestamp30MinutesAgo = $this->dateTime->date('Y-m-d H:i:s', strtotime('-30 minutes'));
// ^^ You might want to drop a debugger here 
// to make sure this timestamp is what you want 😅

/** @var \Magento\Sales\Model\ResourceModel\Order\Item\Collection $collection */
$collection = $this->itemCollectionFactory->create();
$collection->addFieldToFilter('created_at', [
    'gteq' => $timestamp30MinutesAgo
]);

$orderItems = $collection->getItems();

Good luck!

3
  • Thanks! Its work wonderful. One more question, if I want to get data from Sales_order_grid. which Collection Factory I should use? any documentation I can view the spec of each factory?
    – Paul Fan
    Commented May 21, 2021 at 6:29
  • 1
    You can use \Magento\Sales\Model\ResourceModel\Grid\CollectionFactory. github.com/magento/magento2/blob/2.4-develop/app/code/Magento/… Commented May 21, 2021 at 18:57
  • I am not sure of a comprehensive list for all collections. In Magento you can slap Factory at the end of most interfaces, models, etc... and Magento will auto create the factory for you. As far as trying to find the collection you are looking for, I usually just try to find the model I am looking for in a ResourceModel namespace and there should be a corresponding Collection. Commented May 21, 2021 at 18:59

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.