Please give me any example or link for insert and select process without using model in custom module of Magento 2.
Dhara Bhatti
7697 silver badges23 bronze badges
1 Answer 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.
answered May 24, 2019 at 5:47
Prathap Gunasekaran
3,2891 gold badge17 silver badges39 bronze badges
-
Thank you. I tried this code's It works Perfectly...manoji– manoji2019年05月24日 06:08:57 +00:00Commented May 24, 2019 at 6:08
default