简体   繁体   English

用户模型中的Laravel多对一关系

[英]Laravel Multiple One To One Relationship In User Model

im trying to create a one to one relationship with the table user,student and teacher. 我正在尝试与表格用户,学生和老师建立一对一的关系。 The problem is, when i run LARAVEL TINKER, app\\user::find('a123')->teacher it displays the b345 data and doesnt display NULL. 问题是,当我运行LARAVEL TINKER时,app \\ user :: find('a123')-> teacher会显示b345数据,而不显示NULL。 New in Laravel. Laravel的新功能。 Thanks 谢谢

Below is the table with their PK. 下表是其PK的表格。

User table 用户表

user_id | type
a123    |  1
b345    |  2

Student table 学生桌

student_id| name
a123      |  Danny

Teacher table 老师桌

teacher_id| name
b345      |  Mr.Mark

and this BELOW is the models. 下面是模型。

User Model 用户模型

protected $primaryKey = 'user_id';
public function student(){

    return $this->hasOne(student::class,'student_id');
}
public function teacher(){

    return $this->hasOne(teacher::class,'teacher_id');
}

Student Model (Teacher model is just the same with teacher_id as PK) 学生模型 (教师模型,与teacher_id和PK相同)

protected $primaryKey = 'student_id';


public function User()
{
    return $this->belongsTo(User::class,'user_id');
}

From you description, student should belongs to user, also teach 根据您的描述,学生应该属于用户,也应该教

In User Model 在用户模型中


public function student(){

    return $this->hasMany(Student::class,'student_id');
}

In Student Model 在学生模型中


public function user(){

    return $this->belongsTo(User::class,'student_id');
}

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

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