2

I'm learning about Collections, Repositories and DTO, and I'm still trying to figure out what's the best way to query a table to fetch data. I also found that we can use \Magento\Framework\App\ResourceConnection for direct SQL queries.

My question is:

Which way should I use for future projects, since my goal is to use table data to create APIs and also frontend pages? Is there a better way for each case?

1 Answer 1

0

You can use this for test, using ObjectManager like this is not recommanded.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('quote'); //gives table name with prefix
//Select Data from table
$sql = "Select X FROM ".$tableName." WHERE Y;
$result = $connection->fetchAll($sql); // gives associated array, table fields as key in array.

But you can use dependency injection to do this properly

1
  • My point is: I'm trying to understand the reason to use each way to query some data. And some examples, if possible. I was already googling this, but no success. Commented Oct 20, 2022 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.