Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy one table to another in laravel 5

How do i use the following insert into query in laravel 5?

INSERT INTO connection2.table (SELECT * from connection1.table);

I am looking for two different connections, Connection1.table record should goes to Connection2.table.

like image 392
Arvind Avatar asked Apr 16 '16 09:04

Arvind


2 Answers

try

$c1 = DB("Connection1")->select("SELECT * from table")

foreach($c1 as $record){

    DB("Connection2")->table("table")->insert(get_object_vars($record))

}
like image 196
Wistar Avatar answered Oct 19 '22 14:10

Wistar


Since laravel 5.7+ insertUsing(array $columns, Closure|Builder|string $query) is available,
DOCS: https://laravel.com/api/5.8/Illuminate/Database/Query/Builder.html#method_insertUsing
therefore you can now make this whole query in Laravel chaining style like

DB::table('newTable')->insertUsing(
    ['column1', 'column2', 'column3',], // ..., columnN
    function ($query) {
        $query
            ->select(['column1', 'column2', 'column3',]) // ..., columnN
            ->from('oldTable');
            // optional: you could even add some conditions:
            // ->where('some_column', '=', 'somevalue')
            // ->whereNotNull('someColumn')
    }
);

DB here is set-up in app.php 'aliases' as
'DB' => Illuminate\Support\Facades\DB::class,

like image 33
jave.web Avatar answered Oct 19 '22 13:10

jave.web