user7414328
user7414328

Reputation: 21

Two database connection in one query in Laravel

I need to use INSERT INTO...SELECT but using two different database in Laravel. Database A is a local database. Database B is a remote database.

I need something like this :

INSERT INTO local.table1
SELECT * 
FROM remote.table1
ON DUPLICATE KEY UPDATE col1=col1

Is there any way I could achieve this in laravel? Thanks!

Upvotes: 2

Views: 736

Answers (1)

Mihir Bhende
Mihir Bhende

Reputation: 9045

You can have multiple database connections in Laravel. Follow this post.

Then to utilise it :

<?php 

$selectQuery = \DB::connection('remote')
    ->table('table1')
    ->select('column1','column2','column3');

\DB::connection('local')->insert('INSERT INTO table1 (column1, column2, column3) ' . $selectQuery->toSql(), $selectQuery->getBindings());

Upvotes: 4

Related Questions