[英]Laravel: Query with where clause gone wrong
What I am trying to achieve is to allow teachers to import a student into different classes. 我要实现的目标是允许老师将学生导入不同的班级。
Note: A student can be multiple classes. 注意:一个学生可以参加多个班级。
The problem is that when I show the list of students in a select dropdown it should return all students except for students that are not in this class (the class being the page that I am on, app.com/classes/5 for example). 问题是,当我在选择下拉列表中显示学生列表时,它将返回所有学生,除了不在该班级中的学生(该班级是我所在的页面,例如app.com/classes/5) 。
$students = User::join('group_user', 'users.id', '=', 'group_user.user_id')
->role('student')
->where('group_user.group_id', '!=', $id)
->orderBy('users.name', 'asc')
->get();
This works and shows all students that are not in this specific class BUT if a student that's in this class and another class their name appears in the list and as duplicate names. 如果该班级和另一个班级中的一个学生的名字出现在列表中,并且是重复的名字,则该方法可以显示所有不在该班级的学生, 但是会显示该姓名。
What can I do? 我能做什么?
When MySQL's only_full_group_by mode is turned on, it means that strict ANSI SQL rules will apply when using GROUP BY 当MySQL的only_full_group_by模式打开时,这意味着使用GROUP BY时将应用严格的ANSI SQL规则
You should try to select fields from schema on which you can apply group by instead of select *. 您应该尝试从架构中选择可以应用group by的字段,而不要选择*。
$students = User::join('group_user', 'users.id', '=', 'group_user.user_id')
->role('student')
->where('group_user.group_id', '!=', $id)
->select('users.id', 'other fields you used')
->orderBy('users.name', 'ASC')
->groupBy('users.id')
->get();
Not IN is also useful in your case 在您的情况下,“ 不输入”也很有用
User::select('fields you used')
->role('student')
->whereNotIn('id', DB::table('group_user')->where('group_id', $id)->pluck('user_id')) // $id = 5
->orderBy('name', 'ASC')
->get();
Modify your query to use distinct()
like so; 像这样修改查询以使用
distinct()
;
$students = User::join('group_user', 'users.id', '=', 'group_user.user_id')
->role('student')
->where('group_user.group_id', '!=', $id)
->orderBy('users.name', 'ASC')
->distinct()
->get();
You could also groupBy('users.id')
您也可以
groupBy('users.id')
$students = User::join('group_user', 'users.id', '=', 'group_user.user_id')
->role('student')
->where('group_user.group_id', '!=', $id)
->orderBy('users.name', 'ASC')
->groupBy('users.id')
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.