我正在使用两个数据透视表来存储表的两个不同关系。一个关系在插入时工作正常。但下一个抛出以下错误。我不知道是什么原因造成的。
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
sdesk
.approvers
, CONSTRAINTapprovers_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
(id
)) (SQL: insert intoapprovers
(user_id
,request_id
,updated_at
,created_at
) values (2, 6, 2014-04-29 10:54:37, 2014-04-29 10:54:37))
这是我的代码:
UrequestsController.php
public function postCreate() {
$request = new Urequest;
$request->vms = Input::get('vms');
$request->location = Input::get('location');
$request->descr = Input::get('descr');
$request->status = Input::get('status');
//$request->role_group = Input::get('team');
$request->save();
$ruser = new Ruser;
$ruser->user_id = Input::get('userid');
$ruser->urequest()->associate($request);
$ruser->save();
$approver = new Approver;
$approver->user_id = Input::get('aid');
$approver->urequest()->associate($request);
$approver->save();
return Redirect::to('users/dashboard')->with('message', 'Saved!');
}
Approver.php
class Approver extends Eloquent {
protected $fillable = array('request_id', 'user_id');
public function urequest() {
return $this->belongsTo('Urequest','request_id');
}
}
Ruser.php
class Ruser extends Eloquent {
protected $fillable = array('request_id', 'user_id');
public function urequest() {
return $this->belongsTo('Urequest','request_id');
}
}
urequest.php
class Urequest extends Eloquent {
protected $table = 'requests';
protected $fillable = array('vms', 'location', 'descr', 'status');
public function ruser() {
return $this->hasOne('Ruser');
}
public function approver() {
return $this->hasOne('Approver');
}
}
架构
Schema::create('requests', function($table)
{
$table->increments('id');
$table->string('vms', 20);
$table->string('location', 20);
$table->string('descr', 255);
$table->string('status', 20);
$table->timestamps();
});
Schema::create('rusers', function($table)
{
$table->increments('id');
$table->integer('request_id')->unsigned();
$table->foreign('request_id')->references('id')->on('requests');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('approvers', function($table)
{
$table->increments('id');
$table->integer('request_id')->unsigned();
$table->foreign('request_id')->references('id')->on('requests');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
最佳答案
当您在外表中插入/更新的值没有一行时,“外键约束”通常会失败。
在这种情况下,您可能在用户表中没有 user_id 2 或在请求表中没有 request_id 6。
EDIT 刚刚看到 morawcik 在评论中回答了它。
关于php - 在 Laravel 中获取 "Integrity constraint violation: 1452",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23363637/