As title said, i want to query the data from custom table in Observer file. How to do it?

2 Answers 2


1/You can put these codes in your observer. Here is an example for output all data in theme table :


    $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()
    $connection= $this->_resources->getConnection();

    $select = $connection->select()
            ['o' =>  $this->_resources->getTableName('theme')]

    $result = $connection->fetchAll ($select);

You can change the query to insert or delete, update according to zend framework.

The result is : enter image description here

2/The another way is reusing Magento Object Manager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');//insert your custom resource model

    $collection = $productCollection->create()

    foreach ($collection as $product){
        echo 'Name  =  '.$product->getName().'<br>';

Best practice Magento 2 : Use dependency injection

Don't load custom Model or ResourceModel with Object Manager directly like that :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resourceModel = $objectManager->create('Vendor\Module\Model\ResourceModel\Custom');

But you should load it like this :


namespace Vendor\Module\Observer;

use Vendor\Module\Model\ResourceModel\Custom;
use Magento\Framework\Event\ObserverInterface;

class myObserver implements ObserverInterface
    protected $resourceModel;

    public function __construct(
        Custom $resourceModel
        $this->resourceModel = $resourceModel

    public function execute(\Magento\Framework\Event\Observer $observer)
        $event = $observer->getEvent();


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.