3

I have created two migrations:

Migration 1

    Schema::create('responders', function (Blueprint $table) {
        $table->increments('id');
        $table->string('user_id');
        $table->double('latitude', 10, 6);
        $table->double('longitude', 10, 6);
        $table->timestamps();
    });

Migration 2

    Schema::create('devices', function (Blueprint $table) {
        $table->increments('id');
        $table->string('user_id');
        $table->string('device_id');
        $table->string('device_token');
        $table->timestamps();

        $table->foreign('user_id')
            ->references('user_id')
            ->on('responders')
            ->onDelete('cascade');

    });

When I start migration the error message is being thrown:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table devices add constraint devices_user_id_foreign foreign key (user_id) references responders (user_id) on delete cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

I specifically took care that the data types are the same. In this case both are of type string. Why does the foreign key can't be established?

4
  • 1
    The foreign key can't be defined because there is no unique index on the user_id column of the responders table. If you want to define a foreign key, add an index on the referenced column(s). Commented Oct 31, 2015 at 22:40
  • are you sure $table->string('user_id'); should be string not integer? Commented Oct 31, 2015 at 23:22
  • there is some thing also wrong with your logic I think, let me understand so I can help you, responders will have many devices is that correct? and responders belong to a user? is that correct Commented Oct 31, 2015 at 23:35
  • show the schema as output from the server not hand typed Commented Nov 1, 2015 at 1:14

1 Answer 1

1

A foreign key is a column (or columns) that references a column (most often the primary key) of another table. The purpose of the foreign key is to ensure referential integrity of the data. In other words, only values that are supposed to appear in the database are permitted.

Here user_id in responders table isn't a key that's why it's showing this error.

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

Comments

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.