Home > Blockchain >  Defining Laravel Relationship in Custom Primary Key and Foreign Key
Defining Laravel Relationship in Custom Primary Key and Foreign Key

Time:10-27

I have 2 tables and It is One to One Relationship Model Type.

Students Table = id|nik|name|address. Accounts Table = id|nik|username|password.

In this case every student has one account and i took NIK as the $primaryKey in student model. How to define a relationship for that? Thanks in advance.

// Student Model
public function account()
{
    return $this->hasOne(Account::class, 'nik', 'nik');
}

// Account Model
public function student()
{
    return $this->belongsTo(Student::class, 'nik', 'nik');
}

CodePudding user response:

In your students table, you should define a new column with name 'account_id' to represent the student account, and it should be nullable.

        $table->unsignedBigInteger('account_id')->nullable();
  $table->foreign('account_id')->references('nik')->on('accounts');

then , you can use it in your relation:

// Student Model
public function account()
{
    return $this->hasOne(Account::class, 'account_id', 'nik');
}

// Account Model
public function student()
{
    return $this->belongsTo(Student::class, 'account_id', 'nik');
}

CodePudding user response:

You should not have one field (nik) repeated in two tables that's against database normalization. You should create student_id on Account table. That way you would be following Laravel's standard on One to One relationships.

// Student Model
public function account()
{
    return $this->hasOne(Account::class);
}

// Account Model
public function student()
{
    return $this->belongsTo(Student::class);
}
  • Related