skip to Main Content

I have two tables in my Laravel project: teacher_subject and subject. The teacher_subject table has three columns: id, teacher_token and subject_token. And the subject table has three columns: id, subject_token and subject_name. teacher_subject table’s subject_token referencing the subject table’s subject_token. Now, I want to get the subject_name of subject_token wherever the teacher_token is 1. I want to get it by Laravel’s relation method. But, I don’t know how to write the function in teacher_subject model and controller to get the subject_name. Please tell me how to do a many-to-many relation or hasManyThrough relation without a third table?

2

Answers


  1. I’m not sure if I understood your question correctly, but is this what you’re trying to achieve?

    DB::table('teacher_subject')
    ->select('*')
    ->join('subject','subject.subject_token','=','teacher_subject.subject_token')
    ->where('teacher_subject.teacher_token','=',1)
    ->get();
    
    Login or Signup to reply.
  2. Well, you certainly don’t need hasManyThrough() as far as I know, hasMany() would suffice. The following is a solution with just two tables. Try it out, I’m not entirely sure if that’s what you want.

    namespace AppModels;
    
    use IlluminateDatabaseEloquentModel;
    
    class TeacherSubject extends Model
    {
        public function subjects()
        {
            return $this->hasMany(Subject::class, 'subject_token');
        }
    }
    
    namespace AppModels;
    
    use IlluminateDatabaseEloquentModel;
    
    class Subject extends Model
    {
        public function teacherSubjects()
        {
            return $this->hasMany(TeacherSubject::class, 'subject_token');
        }
    }
    

    Now, you can do the following

    $subject = Subject::with('teacherSubjects')->find(1);
    dd($subject, $subject->teacherSubjects);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search