在Laravel中使用字符串数据类型创建外键

时间:2019-05-07 09:45:47

标签: laravel

我有两个桌子。一个是学生出席,另一个是学生。现在,我想在这两个表之间设置一个外键。而且我还有要设置外键的字符串数据类型,但它给了我错误。下面是我的代码。对此进行回顾...

// students_attendances表

public function up()
    {
        Schema::create('students_attendances', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('class_id')->index()->unsigned()->nullable();
            $table->string('student_id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('attendance');
            $table->timestamps();

            $table->foreign('student_id')->references('student_id')->on('students')->onDelete('cascade');


        });
    }

//学生桌

 public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->increments('id');
            $table->string('student_id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('DOB');
            $table->integer('students_class_id')->index()->unsigned()->nullable();
            $table->string('gender');
            $table->string('blood_group');
            $table->string('religion');
            $table->string('photo_id');
            $table->string('student_address');
            $table->integer('student_phone_no');
            $table->string('guardian_name');
            $table->string('guardian_gender');
            $table->string('guardian_relation');
            $table->string('guardian_occupation');
            $table->integer('guardian_phone_no');
            $table->string('email')->unique();
            $table->string('NIC_no');
            $table->string('guardian_address');
//            $table->string('document_id');
            $table->string('username');
            $table->string('password');
            $table->timestamps();
        });
    }

1 个答案:

答案 0 :(得分:1)

在学生表中更改

 $table->string('student_id');

$table->string('student_id')->unique();

要用作外键,它必须是唯一键。

因此,新的迁移将是

Schema::table('students', function (Blueprint $table) {
           $table->unique("student_id");
        });