当我询问如何过滤有关系的数据时,有人推荐我使用spatie/laravel-query-builder来过滤/搜索数据。我仍然对此感到困惑。
我要做的是:过滤/搜索角色为‘Student’(关系)的数据,并包含'x‘这个词。
在添加任何空间/查询构建器代码之前使用mycontroller.php
public function searchStudent(Request $request)
{
$user = Auth::user(); // Untuk Photo Profile
// menangkap data pencarian
$search = $request->table_search;
// This part is the code that supposed to filter the search that has relation to data named Student in name column
$search = User::whereHas('roles', function($q){
$q->where('name', 'Student');
})->where('name','like',"%".$search."%")
->orWhere('nisn','like',"%".$search."%")
->orWhere('username','like',"%".$search."%")
->get();
// // what I got is actually the normal search, so all other relation than Student also show up
return view('pages.admin.user.student.showStudentFiltered', compact('search', 'user') );
}我得到的只是一个老的常规搜索。它们只显示包含“x”字的所有数据,而不显示它们之间的关系。
我想要的搜索数据示例:搜索词'A‘具有'Student’角色的用户
Aqua|角色:学生
Armin|角色:学生
阿尔卑斯|角色:学生
我得到的是:
管理员|角色:管理员
阿姆斯特丹|角色:教师
Amel|角色:教师
Aqua|角色:学生
Armin|角色:学生
阿尔卑斯|角色:学生
有人知道如何使用spatie/laravel-query-builder或如何获得我想要的过滤/搜索功能吗?我需要重写哪些代码?
发布于 2021-08-30 10:08:11
查询构建器whereHas的底层SQL不连接,它只是一个额外的where子句。with将为您连接。
User::with('roles')->whereHas('roles', function($q){
$q->where('name', 'Student');
})https://stackoverflow.com/questions/68982046
复制相似问题