Php 搜索函数返回Laravel中不需要的结果

Php 搜索函数返回Laravel中不需要的结果,php,laravel,Php,Laravel,我做了一个搜索函数,它看起来像是在工作,而不是一个where子句。我希望结果中不要显示尚未发布的项目 因此,即使满足搜索条件,也不应在页面上显示数据库中的项是否已发布=0 这是我的职责 public function search(Request $request) { $searchText = strip_tags($request['q']); $seachLocation = strip_tags($request['l']); $columns =['al

我做了一个搜索函数,它看起来像是在工作,而不是一个
where
子句。我希望结果中不要显示尚未发布的项目

因此,即使满足搜索条件,也不应在页面上显示数据库中的项是否已发布=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

打印出SQL,你就会明白为什么了。SQL将OR周围的条件分组,这意味着分别计算条件1或条件2和条件3

这就是为什么要用括号嵌套条件,以便始终计算条件3:

(条件1或条件2)和条件3

Laravel也是如此,嵌套的方式是回调:

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

您可以始终使用
$query->toSql()
查看生成的SQL的表示形式。

谢谢。我已经试过了,但仍然能看到所有的结果。我已经添加了问题中的sql,您仍然有其他or条件。是的,因为他们正在其他表中查找。嗯。。。我已经回答了你为什么会这样的问题,我想你需要从这里开始。。。但我会给你一个提示。。。将完整条件分组到回调下。