【问题标题】:Laravel validation not exists in table表中不存在 Laravel 验证
【发布时间】:2018-11-27 14:33:45
【问题描述】:

我有两个表,第一个是学生表,第二个是课程学生表。他们在学生和课程表之间有 m2m 关系。我想检查一下,student_id 是否存在于students 表中并且不存在于lesson_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);
}

顺便说一句,我使用的是 laravel 5.6

【问题讨论】:

  • 分享你的数据库结构并只签入一张表lesson_student
  • lesson_student 表只有 course_id 和 student_id,它是数据透视表。 @C2486

标签: php laravel laravel-5 laravel-5.6 laravel-validation


【解决方案1】:

可能你想像这样使用unique 规则:

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

编辑

当您在评论中更新和解释时,您希望在 lesson_student 表中拥有唯一的 student_id 和 course_id。然后你可以使用:

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

【讨论】:

  • student_id 在课程学生表中不是唯一的。 course_student 表有lesson_id 和student_id。它是一个数据透视表。 course_id 和 student_id 都是唯一的。
  • @Nevermore 我是这么认为的,但是您在问题中没有提到这一点。那么在运行此请求时,您的课程 ID 在哪里?
  • Nabialek 我的错,你是对的。我错过了。我用完整的代码更新了问题。对不起。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-04
  • 2020-10-29
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 2017-10-04
相关资源
最近更新 更多