Laravel: Copy models/rows from one connection to another
Asked Answered
F

2

6

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?

Flashing answered 28/6, 2019 at 1:53 Comment(0)
P
1

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

Pupil answered 17/4, 2020 at 13:9 Comment(0)
G
0

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

Garb answered 28/6, 2019 at 7:35 Comment(2)
This solution will fail if the user doesn't exist on the connection2 before executing the save methodWhitson
You can add $user->exists = false; before the save() to create a non-existent userBuckles

© 2022 - 2024 — McMap. All rights reserved.