4

Please give me any example or link for insert and select process without using model in custom module of Magento 2.

1

Try this,

Object Manager :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('employee'); //gives table name with prefix

//Select Data from table
$sql = "Select * FROM " . $tableName;
 $result = $connection->fetchAll($sql); // gives associated array, table fields as key in array.

//Insert Data into table
$sql = "Insert Into " . $tableName . " (emp_id, emp_name, emp_code, emp_salary) Values ('','XYZ','ABD20','50000')";
 $connection->query($sql);

//Update Data into table
$sql = "Update " . $tableName . "Set emp_salary = 20000 where emp_id = 12";
$connection->query($sql);

Di method :

<?php
protected $_resourceConnection;
protected $_connection;
public function __construct(
  \Magento\Framework\App\ResourceConnection $resourceConnection
) {
   $this->_resourceConnection = $resourceConnection;
}
public function getCollection()
{   
   $selectData = $this->_resourceConnection->getConnection();
   //Your custom sql query
   $query = "SELECT * FROM ( SELECT * FROM TABLE_NAME WHERE customer_id IN ( 0, 5 ) ORDER BY feed_id DESC ) AS t1 GROUP BY position limit 0,5"; 

   $collection = selectData->fetchAll($query);
   return $collection;
}
public function insertQuery(){
   $insertQuery = $this->_resourceConnection->getConnection();
   //Your custom sql query
   $saveQuery = "SELECT * FROM ( SELECT * FROM TABLE_NAME WHERE customer_id IN ( 0, 5 ) ORDER BY feed_id DESC ) AS t1 GROUP BY position limit 0,5"; 

   $save = $insertQuery->fetchAll($query);
}
}

Hope this helps.

1
  • Thank you. I tried this code's It works Perfectly... – manoji May 24 '19 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.