Magento – Magento 2: Multiple Database Connection

databasemagento2multiple

I'm using below script to connect for my another database.

https://www.maxpronko.com/blog/new-database-connection-in-magento-2

I stuck after

Next step is to configure resource model to use new connection. The
di.xml configuration file will help to set new resource name to
resource model.

Or any better way?

Best Answer

I was looking for the same solution and came across this:

https://blog.hauri.me/magento2-custom-database-connection.html

I didn't implement the resource model part since I don't need it now but the following part helped me a lot.

/** @var Magento\Framework\App\ResourceConnection $this->resourceConnection **/ $connection = $this->resourceConnection->getConnection('custom');

I use it my code like this (this is part of controller for test purposes) in my code to get a custom connection

public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Framework\App\ResourceConnection $resourceConnection
)
{
    parent::__construct($context);
    $this->_resourceConnection = $resourceConnection;
}

public function execute()
{
    $connection = $this->_resourceConnection->getConnection('custom');
    $select = $connection->select()
        ->from(
            ['tt' => 'testtable']
        );
    $data = $connection->fetchAll($select);

    print_r($data);
}

All the rest just like in here https://www.maxpronko.com/blog/new-database-connection-in-magento-2

I hope this helps!

Related Topic