简体   繁体   中英

Laravel where clause is not returning data after multiple orWhere clauses?

I am using laravel 6.10 version in that I am implementing search,

I have 3 tables

1) course_category

2) course_sub_category

3) course [course_id_category(foreign key),course_sub_category_id(foreign key)]

below is my code

$course = $request->searchItem;

    if ($course=="") {
        $Courses = DB::table('course')
            ->join('course_category', 'course.course_category_id', '=', 'course_category.id')
            ->select('course.*','course_category.title as category_title','course_category.thumb as category_thumb')
            ->orderBy('course.title','asc')
            ->paginate(15);
    }
    else{
        $Courses = DB::table('course')
            ->join('course_category', 'course.course_category_id', '=', 'course_category.id')
            ->join('course_sub_category', 'course.course_sub_category_id', '=', 'course_sub_category.id')
            ->select('course.*','course_category.title as category_title','course_category.thumb as category_thumb')
            ->where('course.title', 'LIKE', '%'.$course.'%')
            ->orWhere('course_category.title', 'LIKE', '%'.$course.'%')
            ->orWhere('course_sub_category.title', 'LIKE', '%'.$course.'%')
            ->get();
    }

在此处输入图片说明

when i am retunring the values i am gatting 0 arrays but when i am removing one orwhere from existing my query is working and its returnig we all values with match

means when i am using multiple orWhere in laravel my where is not working, please share the solution on same.

->orWhere doesnt work like typical SQL. You should use it like that:

$Courses = DB::table('course')
            ->join('course_category', 'course.course_category_id', '=', 'course_category.id')
            ->join('course_sub_category', 'course.course_sub_category_id', '=', 'course_sub_category.id')
            ->select('course.*','course_category.title as category_title','course_category.thumb as category_thumb')
             ->where(function($query) use ($course){
    $query->where('course.title', 'LIKE', '%'.$course.'%')
    $query->orWhere('course_category.title', 'LIKE', '%'.$course.'%')
    $query->orWhere('course_sub_category.title', 'LIKE', '%'.$course.'%')
})
->get();

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