Home > Enterprise >  how to get one tables value with the other tablels's column relationship in laravel?
how to get one tables value with the other tablels's column relationship in laravel?

Time:12-11

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?

CodePudding user response:

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();

CodePudding user response:

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 App\Models;

use Illuminate\Database\Eloquent\Model;

class TeacherSubject extends Model
{
    public function subjects()
    {
        return $this->hasMany(Subject::class, 'subject_token');
    }
}
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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);
  • Related