【问题标题】:Can't figure out a query to upsert collection into a tablr无法确定将集合插入表的查询
【发布时间】:2021-05-28 18:06:04
【问题描述】:

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

我已将集合字段放入数组中。

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');
    }

现在我想插入它们,如果表中不存在学生 ID 和出勤日期的行,否则如果它已经存在则更新。 这是查询:

        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

【问题讨论】:

    标签: mysql database laravel collections


    【解决方案1】:

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

    $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 将查询所有与指定字段匹配的行并更新这些行,然后插入与给定字段不匹配的行。

    【讨论】:

    • 如果记录已经存在则只插入不更新
    【解决方案2】:

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

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

    【讨论】:

    • 把它改成这个 'SmStudentAttendance::upsert( ['attendance_date' => $date, 'student_id' => $temp_id, 'attendance_type' => 'P'], ['attendance_date' = > $temp_attendancedate, 'student_id' => $temp_id], ['attendance_type' => $temp_attendance] );'
    猜你喜欢
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多