简体   繁体   中英

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

I have a simple Article Model and a User Model.

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

Therefore my article migration has a foreign key called "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.

{!! 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.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( tags . articles , CONSTRAINT articles_user_id_foreign FOREIGN 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))

Here is my Store Method on my AriclesController:

    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.

How do I save an article into my database?

Make sure you have user_id in the fillable property of your Article model.

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

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.

I have faced this error a couple times when running migration for existing table. The cause were any of below:

  1. the type of 'user_id' and users 'id' is different. for example when 'user_id' is INT and users 'id' is BIGINT.

  2. the column 'user_id' is not empty, you need to makeit nullable

  3. there are values in column 'user_id' that do not exist in users 'id'

I was experiencing this issue, since I was updating an existing table, with existing data, hence adding a foreign key was causing an issue since there was no default foreign key to assign to the entries. I solved this by first removing data from the table, then running the migration afresh

For me what worked was by adding nullable() also with Laravel 7+ you can do foreignId so for your case $table->foreignId('user_id')->nullable()->constrained()->cascadeOnDelete();

And for the rollback $table->dropForeign(['user_id']); and then $table->dropColumn('user_id');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM