[英]Laravel Pivot Column Filtering
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.
Users()函数是一个belongsToMany关系。
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 还有我的course_users表列:user_id,course_id,role_id
This codes running properly. 此代码可以正常运行。
But, when I looked to queries, I saw two SQL queries for this situation. 但是,当我查询时,针对这种情况,我看到了两个SQL查询。 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.
但是它只会获取第一个变量$ teachers,而不是$ 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.