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.
try
$c1 = DB("Connection1")->select("SELECT * from table")
foreach($c1 as $record){
DB("Connection2")->table("table")->insert(get_object_vars($record))
}
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With