laravel 如何在laaravel 8中检查搜索查询是否包含某些结果

crcmnpdw  于 2023-01-21  发布在  其他
关注(0)|答案(2)|浏览(144)

我正在尝试查找搜索查询是否包含结果,如果不包含,则返回null,此处是代码,但即使数据库中不存在搜索,它也会显示以前的搜索结果

if (!empty($searchInput)) {
    $complexityLevel->join('organizations', 'complexity_levels.organization_id', '=', 'organizations.id');
    $complexityLevel->where("complexity_levels.name", "like", "%$searchInput%")
        ->orWhere("complexity_levels.experience_range_start", "like", "%$searchInput%")
        ->orWhere("complexity_levels.experience_range_end", "like", "%$searchInput%")
        ->orWhere("organizations.name", "like", "%$searchInput%")
    $complexityLevel->select('complexity_levels.*', 'organizations.name');                   
} 

if (!empty($complexityLevel))  {
    return  $complexityLevel->orderBy($sortBy, $sortOrder)->paginate($pageSize);
}
return null;
fgw7neuy

fgw7neuy1#

在你的例子中,你要检查$complexityLevel是否不为空。但是它不会为空,因为它是一个查询,而不是你所期望的集合。要完成你想要做的事情,你需要像这样的代码:

if (!empty($searchInput)) {
    $complexityLevel->join('organizations', 'complexity_levels.organization_id', '=', 'organizations.id')
        ->select('complexity_levels.*', 'organizations.name')
        ->where("complexity_levels.name", "like", "%$searchInput%")
        ->orWhere("complexity_levels.experience_range_start", "like", "%$searchInput%")
        ->orWhere("complexity_levels.experience_range_end", "like", "%$searchInput%")
        ->orWhere("organizations.name", "like", "%$searchInput%")
        ->orderBy($sortBy, $sortOrder)
        ->paginate($pageSize);                   
} 
return count($complexityLevel) ? $complexityLevel : null;
mwngjboj

mwngjboj2#

如果要检查$complexityLevel是否不为空,可以使用-> isNotEmpty()
在您的查询案例中

if (empty($searchInput)) {
  return null;
}

$complexityLevel->query()
   ->join( ... )
   ->where( ... )
   ....
   ->orderBy($sortBy, $sortOrder)
   ->paginate($pageSize);

if ($complexityLevel->isNotEmpty()) {
  return $complexityLevel;
}

return null;

也可以在空时检查

if ($complexityLevel->isEmpty()) {
  return null;
}

以下是一些参考资料:https://laravel.com/api/8.x/Illuminate/Contracts/Pagination/Paginator.html

相关问题