【发布时间】:2015-10-09 18:28:26
【问题描述】:
我有 3 个表用户、帖子和 cmets。用户和帖子之间的关系还可以。我可以存储新帖子。但是,如果我评论帖子,我会收到以下错误消息:
错误信息
Connection.php 第 631 行中的 QueryException: SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(
blog.comments,CONSTRAINTcomments_post_id_foreignFOREIGN KEY (post_id) REFERENCESposts(@987654326 @)) (SQL: 插入comments(body,user_id,updated_at,created_at) 值(新评论, 1, 2015-07-20 14:16:07, 2015-07- 20 14:16:07))
迁移用户
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
迁移帖子
Schema::create( 'posts', function ( Blueprint $table ) {
$table->increments( 'id' );
$table->integer( 'user_id' )->unsigned();
$table->string( 'title' );
$table->text( 'body' );
$table->timestamps();
$table->foreign( 'user_id' )->references( 'id' )->on( 'users' );
} );
迁移cmets
Schema::create('comments', function (Blueprint $table) {
$table->increments( 'id' );
$table->integer( 'user_id' )->unsigned();
$table->integer( 'post_id' )->unsigned();
$table->text( 'body' );
$table->timestamps();
$table->foreign( 'user_id' )->references( 'id' )->on( 'users' );
$table->foreign( 'post_id' )->references( 'id' )->on( 'posts' );
});
模型用户
protected $fillable = [
'name',
'email',
'password'
];
public function posts() {
return $this->hasMany( 'App\Post' );
}
public function comments() {
return $this->hasMany( 'App\Comment' );
}
模特发帖
protected $fillable = [
'title',
'body'
];
public function user() {
return $this->belongsTo( 'App\User' );
}
public function comments() {
return $this->hasMany( 'App\Comment' );
}
模型评论
protected $fillable = [
'body'
];
public function user() {
return $this->belongsTo( 'App\User' );
}
public function post() {
return $this->belongsTo( 'App\Post' );
}
评论控制器
public function store( CommentRequest $request ) {
Auth::user()->comments()->create( $request->all() );
return redirect()->back();
}
PostController $request->all()
"_token" => "TzdItNKU3TChVg50vAqdy1CYCrIR562l4Wv2z6ef"
"title" => "New Post"
"body" => "New text"
CommentController $request->all()
"_token" => "TzdItNKU3TChVg50vAqdy1CYCrIR562l4Wv2z6ef"
"body" => "New Comment"
【问题讨论】:
标签: laravel foreign-keys constraints relationship