我有两个表,第一个是学生表,第二个是lesson_student表。学生和类(class)表之间存在 m2m 关系。我想检查,如果student_id存在于students表中但不存在于lesses_student表中,则将其插入。我使用 exists
来检查学生表,但我不知道如何检查它在 Lesson_student 表中是否不存在。
public function store(Request $request, Lesson $lesson) {
$rules = [
'student_id' => 'required|exists:students,id'
];
$this->validate($request, $rules);
$lesson->students()->attach($request->student_id);
return $this->showAll($lesson->students);
}
顺便说一句,我正在使用 laravel 5.6
最佳答案
您可能想使用unique规则如下:
$rules = [
'student_id' => 'required|exists:students,id|unique:lesson_student:student_id'
]
编辑
正如您在评论中更新和解释的那样,您希望在 lesson_student
表中拥有唯一的 Student_id 和 Lesson_id。然后你可以使用:
$rules = [
'student_id' => [
'required',
'exists:students,id',
\Illuminate\Validation\Rule::unique('lesson_student', 'student_id')
->where('lesson_id', $lesson->id),
]
];
关于php - Laravel 验证表中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50914670/