本文介绍了Laravel 5违反完整性约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了 laracast系列,并停留在某个位置. /p>

通过尝试提交博客帖子,我收到以下错误消息:

奇怪的是,已提交的文章存储在数据库中,并且也出现在我的文章视图中.

ArticlesController:

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

商品型号:

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

模式:

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

    });
}

你知道例外的原因是什么吗?

解决方案

您可以尝试省略此行

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

因为您已经将文章保存为

Auth::user()->articles()->save(new Article($request->all()));

I followed a laracast series and stuck at some point.

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

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?

解决方案

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

这篇关于Laravel 5违反完整性约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 13:53