路线
Route::group(['middleware'=>['auth:api', \App\Http\Middleware\OnlyRegisteredUsers::class]], function(){
Route::post('commentOnPost','UserController@commentOnPost');
});
迁移 创建此迁移后,我已运行php artisan migration命令
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('post_id');
$table->foreign('post_id')->references('id')->on('posts');
$table->string('comment');
$table->boolean('hide')->default(0);
$table->timestamps();
});
}
控制器 它在控制器中显示错误
public function commentOnPost(Request $request){
$userid = $request->user()->id;
$postid = $request->get('post_id');
$comment = trim($request->get('comment'));
//dump($comment);
$user = User::where(['id'=>$userid, 'hide'=>0])->first();
$post = DB::table('posts')->where(['id'=>$postid])->first();
if($user && $post && $comment){
DB::table('comments')->insert([
'user_id' => $userid,
'post_id' => $postid,
'comment' => $comment,
'hide' => 0,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
return ['message'=>'ok'];
}else{
return abort('403', 'Invalid Request');
}
}
我收到一个错误SQL异常:SQL完整性约束 违反例外
答案 0 :(得分:1)
您应该尝试以下操作:
public function commentOnPost(Request $request){
$userid = $request->user()->id;
$postid = $request->get('post_id');
$comment = trim($request->get('comment'));
//dump($comment);
$user = User::where(['id'=>$userid, 'hide'=>0])->first();
$post = DB::table('posts')->where(['id'=>$postid,'hide'=>0])->first();
if($user && $post && $comment){
DB::table('comments')->insert([
'user_id' => $user->id,
'post_id' => $post->id,
'comment' => $comment,
'hide' => 0,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
return ['message'=>'ok'];
}else{
return abort('403', 'Invalid Request');
}
}
答案 1 :(得分:0)
我已经在我的系统上测试了此代码,只有一个小错误
$post = DB::table('posts')->where(['id'=>$postid])->first();
应该是
$post = DB::table('posts')->where(['id'=>$postid,'hide'=>0])->first();