I am new to Magento 2 and I want to get all data from sales_order_item table in Magento 2.
How to get that can anyone answer?
Try this,
DI Method :
Inject sales order item class in your constructor
protected $itemFactory;
public function __construct(
....
\Magento\Sales\Model\Order\ItemFactory $itemFactory,
....
) {
....
$this->itemFactory = $itemFactory;
....
}
then in your function add the below code to get values from it
try {
$order = $this->itemFactory->create()->getCollection();
foreach ($order as $items) {
$items->getItemId(); // similarly you can get all the values from slaes_order_item table
}
} catch (\Exception $e) {
error_log($e->getMessage());
}
For more information Follow this answer
Hope this helps.
Magento 2 has service contact class for almost most of all tables(entities).
So for this table, magento has a service contact class
Magento\Sales\Api\OrderItemRepositoryInterface::getList($searchCriteria)
. Using this interface for getting the all data of sales_order_item
table data.
<?php
namespace MagentostackExchange\Test\Model;
class OrderItems {
/**
* @var \Magento\Framework\Api\SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var \Magento\Sales\Api\OrderItemRepositoryInterface
*/
private $orderItemRepository;
public function __construct(
\Magento\Sales\Api\OrderItemRepositoryInterface $orderItemRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->orderItemRepository = $orderItemRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
public function getALlItemofOrderItem(){
$searchCriteria = $this->searchCriteriaBuilder->create();
$orderItemList = $this->orderItemRepository->getList($searchCriteria);
if($orderItemList->getTotalCount() >= 0)
{
foreach ($orderItemList->getItems() as $orderItem)
{
echo '<pre>';
print_r($orderItem->getData());
}
}
}
}
protected $_resource;
public function __construct(
\Magento\Framework\App\ResourceConnection $resource
) {
$this->_resource = $resource;
}
$connection = $this->_resource->>getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
$tablename = $connection->getTableName('sales_order_item');
$query = "select * from ".$tablename;
$connection->fetchAll($query);