0
votes

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. New in Laravel. Thanks

Below is the table with their 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)

protected $primaryKey = 'student_id';


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

1 Answers

0
votes

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