My codes:
$course = Course::find(1);
$teachers = $course->Users()->where('role_id', 1)->get();
$students = $course->Users()->where('role_id', 2)->get();
In this solution, I have two different user types. Users() function is a belongsToMany relationship.
public function Users()
{
return $this->belongsToMany(User::class, 'course_users')->withPivot('role_id');
}
And my course_users table columns: user_id, course_id, role_id
This codes running properly.
But, when I looked to queries, I saw two SQL queries for this situation. I want to use only one query and get only filtered values to suitable variables for performance. How can I do it?
I tried below code. But it only fetches first variable $teachers, but not $students.
$users = $course->Users();
$teachers = $users->where('role_id', 1)->get();
$students = $users->where('role_id', 2)->get();
What is your opinions? Thank you.
If having just one query is important, you can load the data like this:
$users = $course->Users()->whereIn('role_id', [1, 2])->get();
And then use the collection to filter data:
$teachers = $users->where('role_id', 1);
$students = $users->where('role_id', 2);
Thanks. I solved like this.
$users = $course->Users()->whereIn('role_id', [1, 2])->get();
$teachers = $users->where('pivot.role_id', 1);
$students = $users->where('pivot.role_id', 2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.