php - 使用 Eloquent 更新数组列表中的多个 id

标签 php mysql laravel eloquent

我已将 id 数组传递给 Controller ​​,并将其收集在学生变量内。我想为数组中的每个 id 更新数据库列“lecture_id_FK”。我不确定如何使用数组 id 来查找学生。 Laravel 中的新功能。

Controller

public function setLecture($lecture,$student)
{   
    $students = student::whereIn('student_id', $student)->get();
    $students->lecture_id_FK = $lecture;
    $students->save();

    //if i type "return $student" will produce -> ai160064,ai160065
}

最佳答案

whereIn 方法采用 array as the second argument 。您可以使用 explode 获取所有学生功能。获取所有要更新的记录后,您可以使用 laravel 中的 update 方法对所有记录进行更新。这样您可能会留下一些如下代码:

public function setLecture($lecture,$student)
{   
    $studentIds = explode(',', $student);
    return student::whereIn('student_id', $studentIds)
        ->update(['lecture_id_FK' => $lecture]);
}

关于php - 使用 Eloquent 更新数组列表中的多个 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55748476/

相关文章:

laravel - 为每个帖子获取用户喜欢

php - 发送多个复选框选项

php - Laravel Eloquent ,当一行满足 2 个条件时,如何从查询中排除行?

php - 如何在搜索按钮中合并所有 2 个表

javascript - 如何使用php在两个时间值之间减去?

mysql - SQL 根据另一个不直接相关的表更新列

laravel - 如何在图表js中显示百分比(%)

php - Symfony 2,如何将表单响应重定向到新窗口

php - 网站加载速度

mysql - 使用紧凑的 Laravel 显示数据