Laravel 5 Integrity constraint violation

2019-07-27 13:51发布

I followed a laracast series and stuck at some point.

I got the following error message by trying to submit a blog post:

QueryException in Connection.php line 713: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (codeshare.articles, CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQL: insert into articles (title, body, published_at, updated_at, created_at) values (lorem, ipsum, 2016-07-19 10:11:49, 2016-07-19 10:11:49, 2016-07-19 10:11:49))

The strange thing is, that the submitted article is stored to the DB and also appears in my articles view.

ArticlesController:

public function store(ArticleRequest $request) {
Auth::user()->articles()->save(new article($request->all()));
Article::create($request->all());
return redirect('articles');
}

Article Model:

public function user() {
$this->belongsTo('App\User'); //user_id
}

Schema:

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->text('body');
        $table->timestamp('created_at');
        $table->timestamp('published_at');

        $table->foreign('user_id')
              ->references('id')
              ->on('users')
              ->onDelete('cascade');

    });
}

Any idea what's the reason for the exception?

1条回答
欢心
2楼-- · 2019-07-27 14:14

You can try to leave out this line

Article::create($request->all());

since you are already saving the article with

Auth::user()->articles()->save(new Article($request->all()));
查看更多
登录 后发表回答