2017-10-19 187 views
1

我已经使搜索功能,看起来像是在工作,而不是一个where子句。我想在结果中不显示尚未发布的项目。搜索功能返回不想要的结果在Laravel

所以如果项目中有published = 0即使符合搜索条件也不应该在页面上显示。

这是我的功能

public function search(Request $request) 
{ 

    $searchText = strip_tags($request['q']); 
    $seachLocation = strip_tags($request['l']); 


    $columns =['alias','description']; 

    $query = Item::select('*'); 

    $query->where('title', 'like', '%'.$searchText.'%'); 
    $query->where('published', 1); 
    foreach($columns as $column) { 
     $query->orWhere($column, 'like', '%'.$searchText.'%', '%'.$seachLocation.'%'); 
    } 

    $query->orWhereHas('category',function($query) use ( $searchText) { 
     $query->where('title', 'like', '%'.$searchText.'%'); 
    }); 

    $query->orWhereHas('country',function($query) use ( $searchText) { 
     $query->where('name', 'like', '%'.$searchText.'%'); 
    }); 

    $items = $query->paginate(5); 
    $searchQuery = $searchText; 
    $searchQueryLoc = $seachLocation; 


    return view('search', compact('items','searchQuery','seachLocation')); 
} 

我已经添加是

$query->where('published', 1); 

应携带这种条件,但我仍然看到页面上未公布的项目。这是为什么?

toSql返回

select * from `items` where `title` like ? and `published` = ? and (`alias` like ? or `description` like ?) or exists (select * from `categories` where `items`.`category_id` = `categories`.`id` and `title` like ?) or exists (select * from `countries` where `items`.`country_id` = `countries`.`id` and `name` like ?) limit 5 offset 0 

回答

3

打印出来的SQL,你就会明白为什么。 SQL组围绕OR的条件,这意味着分别评估condition 1condition 2 AND condition 3

这就是为什么你用括号巢条件,条件3总是评价:

(condition 1 OR condition 2) AND condition 3

同样为Laravel,你的方式巢是回调:

$query->where(function($q) use ($columns, $searchText, $seachLocation) { 
    foreach($columns as $column) { 
     $q->orWhere($column, 'like', '%'.$searchText.'%', '%'.$seachLocation.'%'); 
    } 
} 

你总是可以使用$query->toSql()来查看生成的SQL的表示形式。

+0

谢谢。我已经尝试过,但仍然可以看到所有结果。我已经添加了问题的SQL – Ivan

+0

您仍然有其他或条件。 – Devon

+0

是的,因为他们正在寻找其他表格。 – Ivan