Skip to content
Advertisement

how to successfully add a foreign key constraint to your Database table in laravel using eloquent?

I have a database containing two Tables(students, payments) with id as primary key and another column studentID within the students Table. Am making studentID a foreign key in payments Table.

I am getting this error message:

SQLSTATE[42000]: Syntax error or access violation: 1072 Key column ‘studentID’ doesn’t exist in table (SQL: alter table payments add constraint payments_studentid_foreign foreign key (studentID) references students (id))

The studentID exists in both columns, what could be the possible solution to this. below is what I have done

students table

 public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('studentID');
            $table->string('Programme');
            $table->string('cLevel');
            $table->string('image')->nullable();
            $table->string('surName');
        });
    }

payments table

public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->id();
            $table->foreign('studentID')->references('id')->on('students');
            $table->string('feeType');
            $table->string('Year');
            $table->double('amount', 15,3);
            $table->string('paidBy');
            $table->timestamps();
        });
    }

Advertisement

Answer

You are currently adding the student id 2 times on the students table.

$table->id(); is a helper which makes an Unsigned Big Integer column with an auto-incrementing ID

So on your students table delete this line:

$table->bigInteger('studentID');

On your payments table you should add a new column with the id and the foreign key. Note that it is very important to have the same type for your foreign key as the original table so in this case a unsigned big integer:

$table->unsignedBigInteger('studentID');
$table->foreign('studentID')->references('id')->on('students');

PS: since you are a beginner, you should try to follow Laravel conventions for your naming. This will help in linking the relationships in your code.

The convention would be to rename studentID to student_id

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement