soroush gholamzadeh
soroush gholamzadeh

Reputation: 2784

Laravel 4 - migration and foregin keys issue

I want to use migrations for create 2 tables: users and posts here it is my code for create_users_table:

Schema::create('users', function(Blueprint $table)
    {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('username',50);
        $table->string('password',100);
    });

after that i want to create the create_posts_table:

Schema::create('posts',function(Blueprint $table){
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('title',100);
        $table->text('content');
        $table->unsignedInteger('users_id');
        $table->foreign('users_id')->references('id')->on('users')->onDelete('SET NULL')->onUpdate('CASCADE');
        $table->timestamps();
    });

and here it is my problem:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL  
: alter table 'posts' add constraint posts_users_id_foreign foreign key ('u  
sers_id') references 'users' ('id') on delete SET NULL on update CASCADE)

I reviewed my code and I found out that I can't add onDelete('SET NULL') why?!How can I make it happens?

Upvotes: 1

Views: 63

Answers (1)

Jeff
Jeff

Reputation: 2068

For future reference to others having this issue, the fix is simple: allow your foreign key column to be nullable.

Upvotes: 1

Related Questions