简体   繁体   English

在自定义主键和外键中定义 Laravel 关系

[英]Defining Laravel Relationship in Custom Primary Key and Foreign Key

I have 2 tables and It is One to One Relationship Model Type.我有 2 个表,它是一对一的关系模型类型。

Students Table = id|nik|name|address.学生表 = id|nik|name|address。 Accounts Table = id|nik|username|password.帐户表 = id|nik|用户名|密码。

In this case every student has one account and i took NIK as the $primaryKey in student model.在这种情况下,每个学生都有一个帐户,我将 NIK 作为学生模型中的 $primaryKey。 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.在您的学生表中,您应该定义一个名为“account_id”的新列来表示学生帐户,并且它应该可以为空。

        $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.您不应该在反对数据库规范化的两个表中重复一个字段 (nik)。 You should create student_id on Account table.您应该在 Account 表上创建 student_id。 That way you would be following Laravel's standard on One to One relationships.这样你就会遵循 Laravel 关于一对一关系的标准。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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