Home > Software engineering >  How to join two tables and fetch three columns by join query in laravel..As i m new to laravel i m f
How to join two tables and fetch three columns by join query in laravel..As i m new to laravel i m f

Time:10-08

It is my controller

$courses = Assigncourse::join('teachers', 'teachers.id', '=', 'assigncourses.teacher_id') ->join('courses', 'courses.id', '=', 'assigncourses.course2') ->where('teachers.id', '=', $id) ->get(['teachers.name','courses.id', 'courses.course_title','courses.course_code','courses.course_credit', 'courses.course_type']);

My database:I am trying to fetch these couse1,course2 and course3 individually.

Courses database

CodePudding user response:

You Should learn eloquent Relationship No need for Join Query
In Your AssignCourse.php Model File Make function

 public function teachers()
    {
        $this->belongsToMany(Teacher::class,'teacher_id','id');
    }

  public function courses()
  {
    $this->belongsToMany(Course::class,'course2','id');
  }

So you can get the teachers table data in your Controller by calling with function

$assignCourses = Assigncourse::with(['teachers','courses'])->get(); 
dd($assignCourses);

Hope this Helps

  • Related