简体   繁体   中英

Defining Laravel Relationship in Custom Primary Key and Foreign Key

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');
}

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');
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM