之前已经问过这个问题,但是没有回答。所以我再问一遍。我有一个表格的主题栏目:
id->primary key,auto-increment;
class_id->foreign key->refrences id on classes table;
subject;
and a users table:
id->primary key,auto-increment;
username;
password;
and a classes table:
id->primary,autoincrement;
class;
term;
and a pivot table student_user:
id->primary;
user_id->refrences id on users table;
subject_id->refrences id on subject table;
class_id->foreign,refrences id on classes table;
我有我的模型来定义那里的关系
//User Model
//User.php
public function subjects()
{
return $this->belongsToMany('Subject');
}
public function myclass()
{
return $this->belongsTo('SchoolClass');
}
//Class Model
//SchoolClass.php
public function subjects()
{
return $this->hasMany('Subject','class_id');
}
//Subject Model
//Subject.php
public function term()
{
return $this->belongsTo('SchoolClass');
}
public function student()
{
return $this->belongsToMany('User');
}
现在问题来了。当我尝试将数据插入数据透视表subject_user时,只有我要插入的值数组中的最后一个数据被保存到数据库中。我不知道它是否是外来的约束键只更新行而不是在循环数据时插入新行。我无法弄清楚出了什么问题。下面是我的控制器,看看我的数据是如何插入的。对于关系不太熟悉在laravel
//Save Registered Courses
public function post_proceed_registration()
{
$PageTitle = 'Register Subjects';
$id = Auth::user()->id;
$User = User::find($id);
$class_id = $User->profile->class_id;
$subjects = Input::get('subjects');
$registration = RegistrationCheck::where('class_id',$class_id)->where('user_id',$id)->pluck('status');
if(count(Input::get('students')) != 0)
{
if($registration == 'true')
{
PivotSubject::where('user_id',$id)->where('class_id',$class_id)->delete();
foreach($subjects as $sub_id)
{
$subject = new PivotSubject;
$subject->user_id = $id;
$subject->subject_id = $sub_id;
$subject->class_id = $class_id;
$subject->save();
}
RegistrationCheck::where('class_id',$class_id)->where('user_id',$id)->update(['status'=>'false']);
return Response::Json('Success: Subject/Courses Registered');
}
return Response::Json('Error: You already registered for this Term/Semester.Please Contact ICT for help');
}
return Response::Json('Error:You did not choose any course to register');
}
我被困在这里。任何帮助都会受到欢迎