Stefano Maglione
Stefano Maglione

Reputation: 4160

Laravel insert collection in db

I have retrieved some data from db using:

$filtered = DB::table('tmp_table')->distinct()->select('type','description','note')->get();

and I would like to insert what I have retrieved in another table like:

DB::table('tmp_other')->insert($filtered);

but I receive thie error:

Type error: Argument 1 passed to Illuminate\Database\Query\Builder::insert() must be of the type array, object given

which is the best way to do this?

Upvotes: 0

Views: 9591

Answers (5)

TeaDrinkingProgrammer
TeaDrinkingProgrammer

Reputation: 155

I have found that:

Region::insert($tempCollection->toArray());

Doesn't work when you have appends in the model. This does not happen if you use getAttributes on each model. Therefore, this should be safe:

Region::insert($tempCollection->map(fn($x) => $x->getAttributes())->toArray()

Upvotes: 0

hackernewbie
hackernewbie

Reputation: 1722

You can do it one line, like this:

Region::insert($tempCollection->toArray());

Upvotes: 0

Aleksandrs
Aleksandrs

Reputation: 1509

This will do the trick :)

$filtered = DB::table('tmp_table')->distinct()->select('type','description','note')->get()->toArray();
$to_fill = [];
foreach($filtered as $record) {
  $to_fill[] = (array)$record;
}

DB::table('tmp_other')->insert($to_fill);

Upvotes: 0

user7435594
user7435594

Reputation:

this will do the trick for you try this :)

$filtered = DB::table('tmp_table')->distinct()->select('type','description','note')->get();
$filtered->toArray();

DB::table('tmp_other')->insert($filtered);

Upvotes: 2

apokryfos
apokryfos

Reputation: 40681

The SQL way to do blunk inserts of this is something more native like :

DB::insert(
      "INSERT INTO tmp_other (type,description,note) 
       SELECT DISTINCT type,description,note FROM tmp_table"
); 

This will avoid the whole transfer to webserver/transfer back to the SQL server process.

Upvotes: 2

Related Questions