I'm looking for best practice on how to query to database in observer.
Ok so this is the idea, i use observer to catch event catalog_product_save_after
(which will be fired after product is saved in admin page), after that, i get product id, and query to database to get data. Then after some code, i will update data to database.
I've searched a lot, but what i found is just some direct sql solution (which i don't think is good practice for this). Here is what i've found:
- Magento 2 direct sql query for insert not working
- magento 2 , write custom query in customer_address_entity, We can't save the address
- Magento 2: join custom table with product collection while sql query is running fine
(i was not try the third one)
Ok so here is what i do so far:
events.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_model_service_quote_submit_success">
<observer name="sendEmailCustom" instance="Synergy\Butility\Observer\Quote\Webapi\SubmitObserver" />
</event>
<event name="catalog_product_save_after">
<observer name="saveProduct" instance="Synergy\Butility\Observer\ProductSaveObserver" />
</event>
</config>
ProductSaveObserver.php
<?php
namespace Synergy\Butility\Observer;
use Magento\Framework\Event\ObserverInterface;
class ProductSaveObserver implements ObserverInterface
{
public function __construct(
\Magento\Framework\App\ResourceConnection $resource
) {
$this->_resource = $resource;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$productId = $observer->getProduct()->getId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('catalog_product_flat_32');
$product_query = "SELECT * FROM " . $tableName . " WHERE entity_id = " . $productId;
$product = $connection->query($product_query);
foreach ($product as $data) {
var_dump($product->getData());
}
exit;
// $sql = "UPDATE " . $tableName . " SET customer_type = '" . $this->getCustomerType() . "' WHERE entity_id = " . $this->getEntityId($observer);
// $connection->query($sql);
}
}
Thanks for reading :)