Laravel 5 Integrity constraint violation

那年仲夏 提交于 2020-01-15 10:59:18

问题


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:


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()));


来源:https://stackoverflow.com/questions/38455765/laravel-5-integrity-constraint-violation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!