我想仅在搜索键不为空时才在select查询的where条件上运行。如果搜索键为空,则跳过where where condition。这是我的代码,
$users = User::orderBy('id','asc')
->join('agents', 'users.id', '=', 'agents.user_id')
->select('users.id', 'users.first_name', 'users.last_name', 'users.email')
->where('agents.category', 'like', '%'.$category.'%')
->orWhere('agents.location', 'like', '%'.$operation.'%')
->get();
在此查询中,如果变量$category
为空,则无需在条件中运行。并且$operation
为null需要跳过条件的地方。如何解决这个问题?
答案 0 :(得分:3)
尝试以下方法:
$users = User::orderBy('id','asc')->join('agents', 'users.id', '=', 'agents.user_id')->select('users.id', 'users.first_name', 'users.last_name', 'users.email');
if(!is_null($category)) {
$users = $users->where('agents.category', 'like', '%'.$category.'%')->orWhere('agents.location', 'like', '%'.$operation.'%');
}
$users = $users->get();
或:
$users = User::orderBy('id','asc')->join('agents', 'users.id', '=', 'agents.user_id')->select('users.id', 'users.first_name', 'users.last_name', 'users.email')->where('agents.location', 'like', '%'.$operation.'%');
if(!is_null($category)) {
$users = $users->orWhere('agents.category', 'like', '%'.$category.'%');
}
$users = $users->get();