Aug 28, 2016
18
Level 14
Insert multiple records in one query
Hello again, :)
I have a list of objects ( same object ) and I would like to insert them in the database at once. I have tried with createMany but this method I think ( I haven't investigated ) calls create for each array which results in a query to the database for each object. I would like to query the database something like this:
INSERT INTO example
(example_id, name, value, other_value)
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4')
Any way I can do this with Eloquent? I haven't found anything yet.
Thanks
Level 11
I guess it'is not in the docs, but every model has an insert() method that accepts an array of attributes.
Example:
\App\Example::insert([
[
'name' => 'abc',
'value' => '123',
],
[
'name' => 'def',
'value' => '456',
],
// etc...
]);
Note: it calls query builder's insert, I think timestamps are not generated (at least last time i've used it).
6 likes
Please or to participate in this conversation.