In magento2.x development sometimes speed is crucial. Therefore directly accessing database and writing into tables can save lots of time.
Assuming we need to update a record for a customer eg for setting a default group id:
/**
* @var $resource \Magento\Framework\DB\Adapter\Pdo\Mysql\Interceptor
*/
$default_customer_group_id=1
$customerIds = [1,2,111,444];
$resource->update('customer_entity'
['group_id'=>$default_customer_group_id],
['entity_id in (?)'=>$customerIds,]
);
The code above will update the customers But it won't update customer indexes in elasticsearch (or opensearch) therefore we have to update by ourselves:
/**
* @var $indexerFactory Magento\Framework\Indexer\IndexerInterfaceFactory
*/
$indexer = $indexerFactory->create();
$indexer->load('customer_grid');
$indexer->reinderList($customerIds);
But How On earth I will get an instance of IndexerInterfaceFactory
tbw?
It can be either using ObjectManager:
$objectManager = ObjectManager::getInstance();
$indexerFactory = $objectManager->create(\Magento\Framework\Indexer\IndexerInterfaceFactory::class);
Or via dependency injection upon your constructor:
use \Magento\Framework\Indexer\IndexerInterfaceFactory;
// class Definition here
private $indexer;
public function __construct(
// Rest of services here
IndexerInterfaceFactory $indexerFactory
) {
$this->indexer=$indexerFactory->create();
$this->indexer->load('customer_grid');
}
Magento 2 uses for any class Dependency Injection. Furthermore it auto-injects any class to the constructor as well.
Top comments (0)