我的架构是:
Schema::create('persons', function (Blueprint $table) {
$table->bigInteger('university_id')->unique()->unsigned();
$table->string('category');
$table->string('name');
$table->timestamps();
});
Schema::create('teachers', function (Blueprint $table) {
$table->increments('teacher_id');
$table->bigInteger('university_id')->unsigned();
$table->string('position');
$table->string('courses');
$table->integer('salary');
$table->timestamps();
});
Schema::create('students', function (Blueprint $table) {
$table->increments('student_id');
$table->bigInteger('university_id')->unsigned();
$table->string('year');
$table->string('semester');
$table->string('programme');
$table->integer('rollNum');
$table->timestamps();
});
我有两种形式的字段:
我尝试通过我的控制器以单一方法将数据存储在数据库中,如下所示: 在从表单请求所有数据到变量后,我尝试以下列方式存储数据。
University::create([
'university_id' =>$universityID,
'category' => $category,
'name' => $name
]);
//I passed values of category as Teacher when submitting from teacher form
//and Student while submitting student form.
if($category == 'Teacher'){
Teacher::create([
'university_id' => $universityID,
'position' => $position,
'courses' => $course,
'salary' => $salary
]);
}
if($category == 'Student'){
Student::create([
'university_id' => $universityID,
'year' => $year,
'semester' => $semester,
'programme' => $programme,
'rollNum' => $roll
]);
}
当我提交教师表格时,我希望数据只存储在大学和教师表中,而且确实存在。但是出现了意想不到的问题。 Student表中填充了Null值。我期待条件会阻止运行Student::create([])
那么,只有在从学生表单提交时,我才能在教师表格和大学和学生表格中提交仅在大学和教师表格中存储值,而不会在其中任何一个中提供空值。
答案 0 :(得分:1)
使用if
和else
语句可以使用$university = University::create([
'university_id' =>$universityID,
'category' => $category,
'name' => $name
]);
if($category == 'Teacher') {
Teacher::create([
'university_id' => $university->id,
'position' => $position,
'courses' => $course,
'salary' => $salary
]);
else if($category == 'Student') {
Student::create([
'university_id' => $university->id,
'year' => $year,
'semester' => $semester,
'programme' => $programme,
'rollNum' => $roll
]);
}else{
//Unknown Category name
}
和{{1}}语句,而不是像这样使用。
示例:
{{1}}
如果这对你有用,请告诉我。我认为它的方式非常简单直接。