简体   繁体   中英

Complex query in Laravel using Query Builder

On my website I am trying to implement search functionality. When someone enters keyword I am supposed to find all posts and users that may match that keyword based on posts title or body, or based on users name, username or bio. However I am having trouble with executing this query.

public function search(Request $request) {
    $keyword = $request->get('q');
    $posts = Post::where('deleted', 0)
                            ->where('title', 'like', '%'.$keyword.'%')
                            ->orWhere('body', 'like', '%'.$keyword.'%')
                            ->orderBy('title')
                            ->get();
    $users = User::where('name', 'like', '%'.$keyword.'%')
                            ->where('active', 1)
                            ->orWhere('username', 'like', '%'.$keyword.'%')
                            ->orWhere('bio', 'like', '%'.$keyword.'%')
                            ->orderBy('username')
                            ->get();
    return view('searchresults', compact('users', 'posts'));
}

The specific problem I am having is that after function search $posts variable contains posts which were deleted.

This is what I actually need:

select * from posts where deleted = 0 and (title like $keyword or body like $keyword)

I appreciate any help.

Thanks. :)

Use closure to group where() and orWhere() like this:

$posts = Post::where('deleted', 0)
    ->where(function($q) use($keyword) {
        $q->where('title', 'like', '%' . $keyword . '%')
          ->orWhere('body', 'like', '%' . $keyword . '%');
    })     
    ->orderBy('title')
    ->get();
public function search(Request $request) {
    $keyword = $request->get('q');
    $posts = Post::whereNull('deleted')
                 ->where('title', 'like', '%'.$keyword.'%')
                 ->orWhere('body', 'like', '%'.$keyword.'%')
                 ->orderBy('title')
                 ->get();

    $users = User::where(function($query) use($keyword){
                     $query->where('name', 'like', '%'.$keyword.'%');
                     $query->orWhere('username', 'like', '%'.$keyword.'%');
                     $query->orWhere('bio', 'like', '%'.$keyword.'%');
                 })
                 ->where('active', 1)
                 ->orderBy('username')
                 ->get();

    return view('searchresults', compact('users', 'posts'));
}

Hope it's help you!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM