Laravel 结合数组和字符串的数据库插入

Laravel database insert with combining array and string

我应该插入一个数组,例如 $attendanceList = [18354012,18354013,18354014,18354015]$present = "FALSE",并且对 $attendanceList 的所有项目都相同。如您所见,$attendanceList 是数组,但 $presentString.

当我插入like DB::table("attendance")->insert(["id"=>$attendanceList,"present"=>"FALSE"]) returns 错误。

我该怎么办?配对 $attendanceList$present 的所有项目还是有其他方法?

注意:如果可以的话我不想使用循环

我不确定您为什么不想使用循环。如果你想插入四个单独的行,你将需要一个:

foreach ($attendanceList as $id) {
    DB::table("attendance")->insert(["id" => $id,"present" => $present]);
}

您可以根据数据准备数组并在一个查询中进行批量插入:

<?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