我正在尝试在数据库中进行查询,但是laravel变量正在失去其作用域,并且该查询没有给出任何输出..我尝试使用whereRaw但它不起作用
public function search_user(Request $r)
{
try
{
if(JWTAuth::User()->role != 'Admin')
return response()->json(['status'=>False,'error'=>'You do not have permission to Create User.Please Contact your admin for access.']);
$search_type = $r->search_type;//Possible Values , email , userid , username , phone, role
$search_text = strtolower($r->search_text);
$limit = $r->limit;
$offset = $r->offset;
$role = JWTAuth::User()->role;
$user = User::where($search_type,'Like','%'.$search_text.'%')->skip($offset)->take($limit)->toSql();
$count_of_search = count($user);
if($role == 'Admin')
return response()->json(['status'=>true,'data'=>$user,'view_user'=>True,'add_user'=>True , 'edit_user'=>True,'delete_user'=>True,'total_users'=>$count_of_search],200);
elseif($role == 'User')
return response()->json(['status'=>true,'data'=>$user,'view_user'=>False,'add_user'=>False , 'edit_user'=>False,'delete_user'=>False,'total_users'=>$count_of_search],200);
elseif($role == 'Developer')
return response()->json(['status'=>true,'data'=>$user,'view_user'=>True,'add_user'=>False , 'edit_user'=>False,'delete_user'=>False,'total_users'=>$count_of_search],200);
}
**Query Output**
"select * from `users` where `username` Like ? limit 5 offset 0"
答案 0 :(得分:0)
尝试替换以下行:
$user = User::where($search_type,'Like','%'.$search_text.'%')->skip($offset)->take($limit)->toSql();
通过以下行:
$user = User::where($search_type,'Like','%'.$search_text.'%')->skip($offset)->take($limit)->get();
原因:
toSql()
方法返回sql查询,但是get()
方法实际上执行查询。此外,如果要计算用户数,可以使用count
收集方法。如下:
$count_of_search = $user->count()