Yahya Uddin
Yahya Uddin

Reputation: 28841

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:

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

Upvotes: 6

Views: 1356

Answers (2)

OMR
OMR

Reputation: 12188

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

Upvotes: 1

PtrTon
PtrTon

Reputation: 3835

You can leverage the setConection() method on the eloquent model like so:

$users = User::on('connection1')->where('tenant', 'foo')->get();
foreach ($users as $user) {
   $user->setConnection('connection2');
   $user->save();
}

I found this in another stackoverflow question here

Upvotes: 0

Related Questions