0

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?

1 Answer 1

3

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!

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.