php Laravel 5:违反完整性约束:1452 无法添加或更新子行:外键约束失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29189311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:17:56  来源:igfitidea点击:

Laravel 5: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

phpmysqllaravel

提问by LoveAndHappiness

I have a simple Article Model and a User Model.

我有一个简单的文章模型和一个用户模型。

Article "belongsTo" a User and a User "hasMany" Article.

文章“属于”一个用户和一个用户“hasMany”文章。

Therefore my article migration has a foreign key called "user_id".

因此,我的文章迁移有一个名为“user_id”的外键。

    Schema::create('articles', function(Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->timestamps();
    });

Yet whenever I create an Article where I pass the "user_id" in a hidden field I get an error message.

然而,每当我创建一篇文章,在隐藏字段中传递“user_id”时,我都会收到一条错误消息。

{!! Form::open(array('route' => 'articles.store')) !!}

    {!! Form::hidden('userId', $user->id) !!}

    <div class="form-group">
        {!! Form::label('title', 'Title') !!}
        {!! Form::text('title', null, array('class' => 'form-control')) !!}         
    </div>

    <div class="form-group">
        {!! Form::label('text', 'Write your Article') !!}
        {!! Form::textarea('text', null, array('class' => 'form-control')) !!}          
    </div>

    {!! Form::submit('Create Article', array('class' => 'btn btn-default btn-success')) !!}
{!! Form::close() !!}

This is the error message. And I understand that I doesn't try to insert the value for the 'user_id' into the articles table.

这是错误信息。而且我知道我不会尝试将“user_id”的值插入到文章表中。

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tags.articles, CONSTRAINT articles_user_id_foreignFOREIGN KEY (user_id) REFERENCES users(id)) (SQL: insert into articles(title, body, updated_at, created_at) values (Title, Some text, 2015-03-21 23:19:33, 2015-03-21 23:19:33))

SQLSTATE[23000]: 完整性约束违规:1452 无法添加或更新子行:外键约束失败 ( tags. articles, CONSTRAINT articles_user_id_foreignFOREIGN KEY ( user_id) REFERENCES users( id)) (SQL: insert into articles( title, body, updated_at, created_at) values (Title, Some文本, 2015-03-21 23:19:33, 2015-03-21 23:19:33))

Here is my Store Method on my AriclesController:

这是我的 AriclesController 上的 Store 方法:

    Article::create([
        'title'   => Input::get('title'),
        'body'    => Input::get('text'),
        'user_id' => Input::get('userId')
    ]);

    return Redirect::to('articles');

There are dozens of other open Stackoverflow Questions with a similar title, and I am searching yet unsuccessfully for the answer that fits my specific case, therefore I thank you in advance kind stranger.

还有许多其他开放的 Stackoverflow 问题具有类似的标题,我正在寻找适合我的具体情况的答案但没有成功,因此我提前感谢您的好心陌生人。

How do I save an article into my database?

如何将文章保存到我的数据库中?

回答by Adam Particka

Make sure you have user_idin the fillableproperty of your Article model.

确保您拥有文章模型user_idfillable属性。

http://laravel.com/docs/5.0/eloquent#mass-assignment

http://laravel.com/docs/5.0/eloquent#mass-assignment

回答by The Sammie

I had the same problem. I added a foreign key to a table that already existed and had data and I couldn't run the migrations because it kept failing. The solution to make the migration work was to make the foreign key nullable.

我有同样的问题。我向一个已经存在并有数据的表添加了一个外键,但我无法运行迁移,因为它一直失败。使迁移工作的解决方案是使外键可以为空。

$table->integer('user_id')->nullable()->unsigned();

// then the foreign key
$table->foreign('user_id')->references('id')->on('users');

Hoping it saves someone else time in the future.

希望它在未来节省其他人的时间。