Laravel查询“where”和“orwhere”无法正常工作

时间:2016-08-27 08:49:53

标签: php laravel-5.2 laravel-query-builder

我有以下功能 -

public function search_profile(Request $request)
{
    $search_keyword = $request->search;
    $search_user = $request->user;
    $user_public = User::where('username', $request->user)->first();

    $tags_list = Tag::orderBy('tag', 'asc')->get();
    $bookmarks = Bookmark::orderBy('created_at','desc')->where('bookmarker', $search_user)->where('public', '1')->where('tags', 'rlike', $search_keyword)->orwhere('title', 'rlike', $search_keyword)->orwhere('description', 'rlike', $search_keyword)->orwhere('contents', 'rlike', $search_keyword)->paginate(15);
    $bookmarks_all = Bookmark::orderBy('created_at','desc')->where('bookmarker', $search_user)->where('public', '1')->where('tags', 'rlike', $search_keyword)->orwhere('title', 'rlike', $search_keyword)->orwhere('description', 'rlike', $search_keyword)->orwhere('contents', 'rlike', $search_keyword)->get();
    return view('profile_search')->with('bookmark', $bookmarks)->with('tags_list', $tags_list)->with('bookmarks_all', $bookmarks_all)->with('username', $user_public)->with('search_keyword', $search_keyword);
}

但我甚至从其他bookmarker得到了结果。例如 - 如果$search_keyword = 'laravel'$serach_user = 'zack'。我也从其他用户那里得到了结果。

我是laravel的新人。那么我在查询中做错了什么?

2 个答案:

答案 0 :(得分:3)

您的查询

$bookmarks = Bookmark::orderBy('created_at','desc')->where('bookmarker', $search_user)->where('public', '1')->where('tags', 'rlike', $search_keyword)->orwhere('title', 'rlike', $search_keyword)->orwhere('description', 'rlike', $search_keyword)->orwhere('contents', 'rlike', $search_keyword)->paginate(15);

会产生类似这样的东西

SELECT * FROM bookmarks WHERE bookmarker = $search_user AND public = 1 OR title rlike $search_keyword OR content rlike $search_keyword;

这不是你想要的,因为如果它与标题匹配,它将返回结果。

你最想要的是:

Bookmark::orderBy('created_at','desc')
        ->where('bookmarker', '$search_user')
        ->where('public', '1')
        ->orWhere(function ($query) use ($search_keyword) {
            $query->where('title', 'rlike', $search_keyword)
                  ->where('contents', 'rlike', $search_keyword);
        })
        ->get();

查看advance where

答案 1 :(得分:0)

嘿,Xahed Kamal,请将此查询与像here这样的表一起使用($data = DB::table('table_name')->where('column_name',abcd)->orWhere('column_name',abcd)->get ();)

工作正常

和下一个 $bookmarks = Bookmark::orderBy('created_at','desc')->where('bookmarker', $search_user)->where('public', '1')->where('tags', 'rlike' , $search_keyword)->pluck('id');

$bookmarks_data = Bookmark::whereIn('id',$bookmarks)->orwhere('title', 'rlike', $search_keyword)->orwhere('description', 'rlike', $search_keyword)-> orwhere('contents', 'rlike', $search_keyword)->分页(15);