【发布时间】:2015-03-09 02:01:29
【问题描述】:
我的 Laravel 应用程序出现此错误:
无法添加或更新子行:外键约束失败
这是我的 2 张桌子
用户
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username');
$table->string('password');
$table->string('firstname');
$table->string('lastname');
$table->string('middlename');
$table->string('address');
$table->string('birthday');
$table->string('contact');
$table->string('email');
$table->enum('isAdmin', array(0,1))->default(0);
$table->enum('isTeacher', array(0,1))->default(0);
$table->timestamps();
});
出席率
Schema::create('attendance', function(Blueprint $table)
{
$table->increments('id');
$table->string('status');
$table->string('comment');
$table->integer('student_id')->unsigned();
$table->foreign('student_id')->references('id')->on('users');
$table->string('student_firstname');
$table->string('student_lastname');
$table->integer('teacher_id')->unsigned();
$table->foreign('teacher_id')->references('id')->on('users');
$table->string('teacher_firstname');
$table->string('teacher_lastname');
$table->timestamps();
这是我的模型
用户
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public function attendance()
{
return $this->belongsTo('Attendance');
}
出席率
class Attendance extends Eloquent
{
public function users()
{
return $this->hasMany('User');
}
}
**最后这是我的控制器**
public function postCreateAttendance()
{
$validate = Validator::make(Input::all(), array(
'status' => 'required'
));
if ($validate->fails())
{
return Redirect::route('viewStudent')->withErrors($validate)->withInput();
}
else
{
//$student = User::whereRaw('isTeacher = "0" and isAdmin = "0"')->get();
//$teacher = User::whereRaw('isTeacher = "1" and isAdmin = "0"')->get();
$student = new User();
$teacher = new User();
$attendance = new Attendance();
$student->save();
$teacher->save();
$attendance->save();
$student->student_id = Input::get('3');
$attendance->status = Input::get('status');
$attendance->comment = Input::get('comment');
$attendance->student_firstname = Input::get('student_first');
$attendance->student_lastname = Input::get('student_last');
$attendance->teacher_firstname = Input::get('teacher_first');
$attendance->teacher_lastname = Input::get('teacher_last');
我也试过这个,但它给了我同样的错误。
public function sampleAttendance()
{
User::find(1)->attendance()->insert(array(
'status' => 'present',
'comment' => 'none',
'student_id' => '1',
'student_firstname' => 'student_first',
'student_lastname' => 'student_last',
'teacher_firstname' => 'teacher_first',
'teacher_lastname' => 'teacher_last'
));
请帮忙? :(
【问题讨论】:
标签: laravel laravel-4 eloquent laravel-5