代码之家  ›  专栏  ›  技术社区  ›  Nevermore

表中不存在laravel验证

  •  0
  • Nevermore  · 技术社区  · 7 年前

    我有两张桌子,第一张是学生桌,第二张是学生桌。他们在学生和课程表之间有M2M关系。我想检查一下,如果student_id存在于student表中,而student表中不存在,请插入它。我用 exists 登记学生桌,但我不知道如何检查它不存在于学生桌。

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

    顺便说一下,我用的是拉弗5.6

    1 回复  |  直到 7 年前
        1
  •  2
  •   Marcin Nabiałek    7 年前

    也许你想用 unique 这样的规则:

    $rules = [
       'student_id' => 'required|exists:students,id|unique:lesson_student:student_id'
    ]
    

    编辑

    当您在评论中更新和解释时,您希望在中包含唯一的学生ID和课程ID lesson_student 表。然后您可以使用:

    $rules = [
        'student_id' => [
           'required',
           'exists:students,id',
            \Illuminate\Validation\Rule::unique('lesson_student', 'student_id')
                 ->where('lesson_id', $lesson->id),
         ]
    ];
    
    推荐文章