Home > OS >  How to set the primary key itself as a foreign key in laravel?
How to set the primary key itself as a foreign key in laravel?

Time:12-08

This sounds nooby but I wanted to know if I can make the primary key work as a foreign key in Laravel, and I'am new to Laravel.

So, I have two migrations 'User' and 'Student' as Shown below: User :

 Schema::create('users', function (Blueprint $table) {
            $table->string('uniqueId', 30)->primary();
            $table->text('password');
            $table->string('userType');
            $table->timestamps();
        });

and Student :

Schema::create('students', function (Blueprint $table) {
            $table->string('uniqueId', 30)->primary();
            $table->text('name');
            $table->text('fName');
            $table->text('mName');
            $table->text('addr');
            $table->string('image');
            $table->integer('class');
            $table->integer('roll');
            $table->string('year');
            $table->timestamps();
        });

So, all I wanted was that the primary key in Student (uniqueId) also work as a foreign key that references the 'uniqueId' column from the User table.

Thanks in advance.

CodePudding user response:

This isn't something you do with a migration file, but instead how you set up relationships in your models themselves, In all honesty I would try and steer away from using the same primary key to represent two models and instead add another column to your students table called $table->string('user_id', 30)->index(); then create that relationship inside of your model class like so:

    public function user()
    {
        return $this->hasOne(User::class);
    }

CodePudding user response:

While not necessary, you can add foreign key constraints via migration.

https://laravel.com/docs/8.x/migrations#foreign-key-constraints

CodePudding user response:

You can do something like that:

if (!Schema::hasTable('users')) {
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->text('password');
        $table->string('userType');
        $table->timestamps();
    });
}

if (!Schema::hasTable('students')) {
    Schema::create('students', function (Blueprint $table) {
        $table->increments('id');
        $table->text('name');
        $table->text('fName');
        $table->text('mName');
        $table->text('addr');
        $table->string('image');
        $table->integer('class');
        $table->integer('roll');
        $table->string('year');
        $table->timestamps();
        $table->foreign('user_id', 'fk_users_user_id')
            ->references('id')->on('users')->onUpdate('NO ACTION')->onDelete('cascade');
        });
}
  • Related