2

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!

2
  • u want to select rows from local and insert rows into remote database..am i right? Commented Feb 4, 2019 at 7:15
  • no, I want to select rows from remote and insert into local database @JigneshJoisar Commented Feb 4, 2019 at 7:20

1 Answer 1

4

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());
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work. It seems selectQuery uses 'local' instead of 'remote'. Is it possible I need something else to make this work?
If its different servers altogether then you need to create a table with federated engine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.