问题
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
, CONSTRAINTarticles_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
(id
) ON DELETE CASCADE) (SQL: insert intoarticles
(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