As title said, i want to query the data from custom table in Observer file. How to do it?
1/You can put these codes in your observer. Here is an example for output all data in theme table :
$themeId=3;
$this->_resources = \Magento\Framework\App\ObjectManager::getInstance()
->get('Magento\Framework\App\ResourceConnection');
$connection= $this->_resources->getConnection();
$select = $connection->select()
->from(
['o' => $this->_resources->getTableName('theme')]
);
$result = $connection->fetchAll ($select);
var_dump($result);
You can change the query to insert or delete, update according to zend framework.
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()
->addAttributeToSelect('*')
->load();
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');
$resourceModel->loadBySomething('example');
But you should load it like this :
<?php
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();
$this->resourceModel->loadBySomething('example');
}
}