2

I should insert an array such as $attendanceList = [18354012,18354013,18354014,18354015] and $present = "FALSE" and same for all item of $attendanceList. As you see $attendanceList is array but $present is String.

When I insert like DB::table("attendance")->insert(["id"=>$attendanceList,"present"=>"FALSE"]) returns error.

What should I do? Pairing all item of $attendanceList and $present or there are another ways?

Note: I don't want to use loop if it is possible.

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
Wtow
  • 98
  • 1
  • 8

2 Answers2

1

You can prepare array from your data and do bulk insert in one query:

<?php
$attendanceList = [18354012,18354013,18354014,18354015];
$present = "FALSE";

$insertData = array_map(
    fn($el)=>['id'=>$el, 'present'=>$present],
    $attendanceList
);

$db::table("attendance")->insert($insertData); 

Test Laravel DB insert online

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
  • I think that is better as syntax than a loop but come to the same thing. Maybe I can put the [reference](https://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function). – Wtow May 04 '22 at 07:43
  • 1
    @Wtow, I'm not sure but consider eloquent insert with array process bulk insert instead multiple single inserts in loop – Slava Rozhnev May 04 '22 at 08:08
  • That is good idea to optimize database querry if not possible to optimize loop. – Wtow May 05 '22 at 15:31
0

I'm not sure why you don't want to use a loop. If you want to insert four separate rows, you're going to need one:

foreach ($attendanceList as $id) {
    DB::table("attendance")->insert(["id" => $id,"present" => $present]);
}
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
  • I have some for loop before this statement, so another for loop will increase complexity. Thank you for your answer, but I prefer to not use if it is possible. – Wtow May 02 '22 at 15:35
  • You can not perform this insert without a loop _somewhere_. Stop micro-optimizing. – Alex Howansky May 02 '22 at 15:48