无法找出将 collection 更新插入表中的查询

Can't figure out a query to upsert collection into a tablr

我想在我的模型中插入或更新行 table。但无法弄清楚查询。 SmStudentAttendance 这是我的模型。 $students 是我的 collection.

我已将 collection 字段放入数组中。

foreach ($students as $student) {
        array_push($temp_id, $student->id);
        array_push($temp_lastname, $student->last_name);
        array_push($temp_academic_id, $student->academic_id);
        array_push($temp_attendance, 'P');
        array_push($temp_attendancedate, $date);
        array_push($temp_schoolid, '1');
        array_push($temp_updatedby, '1');
        array_push($temp_createdby, '1');
    }

现在,如果 student_id 和 attendance_date 的行不存在于 table else 更新中(如果它已经存在),我想插入它们。 这是查询:

        SmStudentAttendance::upsert('attendance_type', $temp_attendance, 'attendance_date', $temp_attendancedate, 'student_id', $temp_id, 'created_by', $temp_createdby, 'updated_by', $temp_updatedby, 'school_id', $temp_schoolid, 'academic_id', $temp_academic_id);

我遇到的错误:

Argument 1 passed to Illuminate\Database\Eloquent\Builder::upsert() must be of the type array, string given, called in D:\xampp\htdocs\sms\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 23

错误消息“传递给 Illuminate\Database\Eloquent\Builder::upsert() 的参数 1 必须是数组类型,给定的字符串”,表明第一个参数需要是数组而不是字符串正在设置。

查看 https://laravel.com/docs/8.x/eloquent#upserts 上的文档作为示例。该方法接受两个数组。第一个包含所有要更新的数据,第二个包含唯一标识记录的字段。您将需要更新您的方法调用以匹配此语法。

您正在为列而不是行创建数组,这会导致问题,请考虑使用以下代码:

$studentRows = [];
foreach ($students as $student) {
        $studentRows[] = [ 
              'id' => $student->id,
              'last_name' => $student->last_name,
              'academic_id' => $student->academic_id,
              'attendance_type' => 'P',
              'attendance_date' => $date,
               // .... rest of the fields
       ]
}
SmStudentAttendance::upsert($studentRows, [ 'id', 'last_name', 'academic_id' ], [ 'attendance_type', 'attendance_date' ]);


一般来说,您将要更新插入的行数组传递给它,然后是要匹配的字段数组和要更新的字段数组。然后 Laravel 将使查询找到与指定字段匹配的所有行并更新这些行,然后插入与给定字段不匹配的行。