0

I am using laravel schema builder and here is my code...

    //create links table
    Schema::create('links', function($table){
        $table->increments('id');
        $table->unsignedInteger('user_id');
        $table->unsignedInteger('domain_id');
        $table->string('url');
        $table->softDeletes();
        $table->timestamps();
    });
    Schema::table('links', function($table) {
        $table->index('user_id');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
        $table->index('domain_id');
        $table->foreign('domain_id')->references('id')->on('domains')->onDelete('cascade')->onUpdate('cascade');
    });
}

But i try to save something to this table it throws following error...

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`we`.`links`, CONSTRAINT `links_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `links` (`updated_at`, `created_at`) values (2014-09-04 17:35:53, 2014-09-04 17:35:53)) 

Please suggest if you need anything more to understand this better, help me to fix this.

thanks

1 Answer 1

1

If the SQL statement's to be believed somewhere the app's inserting just the timestamps fields (updated_at, created_at). You need to at least specify an existing user_id for the query. If there are cases where you can insert into links without associating a user, you need to update the links table so links.user_id allows for null values. You can't update a column on an existing table to accept nulls through the schema manager, you'll need to do that through a manual query.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm guessing some part of the process is generating the noted SQL query, which is included in your error: "insert into links (updated_at, created_at) values (2014-09-04 17:35:53, 2014-09-04 17:35:53)". What does the stack trace look like in laravel.log?
1452 Cannot add or update a child row: a foreign key constraint fails (we.links, CONSTRAINT links_user_id_foreign` FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into links (updated_at, created_at) values (2014-09-04 19:12:57, 2014-09-04 19:12:57))`
That's the only line? You're app doesn't have debug option on in app/config/app.php? Other than that, could you post the code for the update operation that's triggering the failure?
I have allowed nullable values and it solved the issue. $table->unsignedInteger('user_id')->nullable(); thanks for your great help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.