Let's say I have table named groups with these data:
+----+---------+------+-------+ | id | user_id | name | color | +----+---------+------+-------+ | 1 | 1 | foo | green | | 2 | 1 | bar | red | | 3 | 1 | baz | | | 4 | 2 | baz | grey | | 5 | 3 | foo | blue | | 6 | 3 | baz | | | 7 | 4 | baz | brown | | 8 | 4 | foo | | | 9 | 4 | qux | black | +----+---------+------+-------+
I'm going to read a csv file and convert it to an array of data like this:
[
[
'user_id' => 2,
'name' => 'foo'
],
[
'user_id' => 2,
'name' => 'bar'
],
[
'user_id' => 2,
'name' => 'baz'
],
[
'user_id' => 2,
'name' => 'qux'
],
[
'user_id' => 2,
'name' => 'tux'
],
]
and insert only new data into database, and skip what already exist in database, in this example, group baz
for user 2.
In Eloquent there are some useful methods like firstOrCreate()
or findOrNew()
that seems to be what I need, but these methods are for only one record, and if I use them I should run them per file line.
while($line = $this->decoder->decode($this->file) {
$row = Group::firstOrCreate($line);
}
Is there any better solution with running less queries?