Doing left join/inner join in many-to-many relations with Eloquent In Laravel 4
-
20-12-2019 - |
سؤال
Is there any way to do inner join using Eloquent in Laravel 4? Because I don't wanna show Courses without users in it.
Actually I have this.
Controller:
$courses = Course::all();
foreach($courses as $course){
$course->users;
}
View:
@foreach($courses as $course)
<h3>{{ $course->course}} :</h3>
@foreach($course->users as $user)
<p> {{$user->username}} </p>
@endforeach
@endforeach
Class User:
public function courses(){
return $this->belongsToMany('Course','course_user','id_usuario');
}
Class Course:
public function users(){
return $this->belongsToMany('User','course_user','course_id','id_usuario');
}
المحلول
I figured out that the method Has(); appears to be like inner join So in the controller i do:
$courses = Course::has('users')->get();
..and that's it :)
نصائح أخرى
Something like this should do, fill in your inner join.
return $this->belongsToMany('Course','course_user','id_usuario')
->join('students', 'student_user.user_id', '=', 'students.id')
->get();
Check out the documentation http://laravel.com/docs/queries#joins for more info!
لا تنتمي إلى StackOverflow