I have table called my_table.

In my_table I have got 4 columns:

ID which is primary and auto increment, name, some_text, serial_number(int).

I want to get only those some_text fields which match with serial_number(int).

For example, if serial_number(int) value is '1', I need to get all those some_text fields which are in the same row with serial_number(int) which values are '1'.

  • Well as SQL query it would look like this: SELECT some_text FROM my_table WHERE serial_number = 1; What classes should I inject into my Block file and what methods should I call to collect these data?
    – Rufus
    Commented Feb 28, 2019 at 10:56
  • If the below answer is useful do accept it so other will use this answer @Rufus Commented Mar 19, 2019 at 6:23

2 Answers 2


You can directly get custom table using objectmanager concept,

    $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
    $connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION'); 
    $result1 = $connection->fetchAll("SELECT * FROM my_table");
echo "<pre>";print_r($result1);


This is proper way using block:

public function __construct(
    Context $context,
    \Namespace\Module\Model\ModuleFactory $modelFactory,
    array $data = array()
) {
    $this->_modelFactory = $modelFactory;
    parent::__construct($context, $data);

You can get collection by factory methods:

public function getCollection(){
                      ->addFieldToFilter('serial_number',array('eq' =>'1'));

Try this to get collection,

In your block add the below code

namespace Vendor\Module\Block;                                              
use Magento\Framework\View\Element\Template;                              
class Block_Name extends Template{
public function __construct(
    \Vendor\Module\Model\model_nameFactory $collectionFactory
) {
    $this->collectionFactory = $collectionFactory;

public function getCollection($productId = '')
    $collection = $this->collectionFactory->create()->getCollection()->addFieldToFilter('serial_number', array(
        'eq' => '1'
    //$this->collectionFactory->create()->getCollection()->addFieldToFilter('serial_number', '1');
    $getCollection = array();
    foreach ($collection as $item) {
        $getCollection[] = $item->getSomeText();  //Get some text
    return $getCollection;

Hope it helps :)

Your Answer

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

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