i want to get order item from order collection on weekly basis and i wrote blow code . i just want to confirm that its right way or we can do better than this way please advice
public function execute()
{
$filepath = 'export/customerlist.csv';
$this->directory->create('export');
$stream = $this->directory->openFile($filepath, 'w+');
$stream->lock();
$header = ['Sku', 'Name', 'Price','Qty','Date'];
$stream->writeCsv($header);
$orders = $this->getOrderCollectionByDateRange();
if($orders->getTotalCount() > 0) {
foreach($orders as $_order) {
$order = $this->orderRepository->get($_order->getEntityId());
foreach ($order->getAllVisibleItems() as $_item) {
$data = [];
$data[] = $_item->getSku();
$data[] = $_item->getName();
$data[] = $_item->getPrice();
$data[] = $_item->getQtyOrdered();
$data[] = $order->getCreatedAt();
$stream->writeCsv($data);
}
}
}
}
public function getOrderCollectionByDateRange(){
$currentDate = $this->date->date('Y-m-d');
$previousDate = $this->date->date('Y-m-d', strtotime($currentDate."-2 days"));
$startDate = date("Y-m-d",strtotime($previousDate)); // start date
$endDate = date("Y-m-d ", strtotime($currentDate)); // end date
$orders = $this->orderCollectionFactory->create()
->addAttributeToFilter('created_at', array('from'=>$startDate, 'to'=>$endDate));
echo $orders->getSelect();
return $orders;
}