Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Copy models/rows from one connection to another

I want to copy an eloquent model from one connection to another.

The way I have done this so far is as so:

$users = User::on('connection1')->where('tenant', 'foo')->get();
User::on('connection2')->insert($users->toArray());

This works most of the time. But there are cases where this does not work. For example:

  • When the model has $hidden attribute
  • When the toArray method for a model is overrided

What is a reliable way to simply copy over some rows to another connection?

like image 480
Yahya Uddin Avatar asked Nov 17 '22 06:11

Yahya Uddin


1 Answers

i think i have found a solution for $hidden attribute & overwriting toArray method

 $users = User::on('connection1')->where('tenant', 'foo')->get();

foreach ($users as $user) {
            $usersArray[] = $user->getAttributes();
        }
User::on('connection2')->insert($usersArray);

if you are using mySql i recommend using bulk insert:

https://www.geeksengine.com/database/data-manipulation/bulk-insert.php

like image 86
OMR Avatar answered Nov 19 '22 10:11

OMR