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



我试图找到搜索查询是否包含结果,如果不是,则返回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;

在您的情况下,您正在检查$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;

如果您想检查$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