在根据数据获得的评分进行搜索时如何排序数据,以及如何针对未评分的数据进行排序

时间:2019-05-28 12:37:30

标签: laravel-5.7

  

我有一个想要进行人力资源管理的项目   在搜索为时显示评级和非评级求职者   雇主。

I have tried this but this only gives jobseekers whose ratings has been set.
public function search(Request $request)
    {
        $query = $request->get('query');
        if (isset($query)) {
            $queryParam = explode(' ', $query);
        } else {
            $queryParam = null;
        }
        $jobseekers = JobSeekers::where(function ($que) use ($queryParam) {
            if (isset($queryParam)) {
                foreach ($queryParam as $queries) {
                    $que->orWhere('job_seekers.category', 'like', '%' . $queries . '%');
                    $que->orWhere('job_seekers.keywords', 'like', '%' . $queries . '%');
                    $que->orWhere('job_seekers.experience', 'like', '%' . $queries . '%');
                }
            }
        })->join('ratings', 'job_seekers.id', '=', 'ratings.js_id')
            ->groupBy('job_seekers.id')
            ->select('job_seekers.id', DB::raw('AVG( ratings.rating )  AS average_rating'))
            ->orderBy('average_rating', 'desc')
            ->get();
        return view('search.search_all', compact('jobseekers'));
    }
    I have a rating table .
    Schema::create('ratings', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('emp_id')->unsigned();
        $table->integer('js_id')->unsigned();
        $table->integer('rating')->unsigned();
        $table->longText('description')->nullable();
        $table->foreign('emp_id')->references('id')->on('employers');
        $table->foreign('js_id')->references('id')->on('job_seekers');
        $table->timestamps();
    });
  

我只获得给出了评级的对象的数据,而没有得到   数据,但没有评级。

1 个答案:

答案 0 :(得分:1)

尝试使用leftJoin()代替join()

JOIN仅选择在联接表中具有数据的结果。

LEFT JOIN选择所有结果并从联接表中附加数据。

public function search(Request $request)
{
    $jobseekers = JobSeekers
        ::when($request->get('query'), function($query) use ($request) {
            $words = explode(' ', $request->get('query'));
            foreach($words as $word){
                $query->orWhere('job_seekers.category', 'like', '%' . $word . '%');
                $query->orWhere('job_seekers.keywords', 'like', '%' . $word . '%');
                $query->orWhere('job_seekers.experience', 'like', '%' . $word . '%');
            }
        })
        ->leftJoin('ratings', 'job_seekers.id', '=', 'ratings.js_id')
        ->groupBy('job_seekers.id')
        ->select('job_seekers.id', DB::raw('AVG( ratings.rating )  AS average_rating'))
        ->orderBy('average_rating', 'desc')
        ->get();

    return view('search.search_all', compact('jobseekers'));
}