为什么具有distinct和group by的查询不返回结果?

时间:2018-08-05 18:34:42

标签: php laravel

我有这个查询来获取“ city”列等于$ search的会议。

   $cities = Conference::
    where('city', 'LIKE', '%'.$search.'%')
    -> distinct()->get(['city']);

但是我也想按会议“ start_date”列的结果排序。但这是行不通的:

$cities = Conference::
   where('city', 'LIKE', '%'.$search.'%')
  ->distinct()->orderBy('start_date', 'asc')
  ->get(['city','start_date']);

例如,如果用户在搜索自动完成字段中引入了“新建”,而该区别项无法正常工作,则它会出现多次,例如“纽卡斯尔”,而不会出现一次。

你知道为什么吗?

像这样,使用分组依据,当用户介绍“ New”时,未显示任何结果,但应显示“ Newcastle”:

 $cities = DB::raw("SELECT city, min(start_date) FROM conferences WHERE city LIKE '%search%' 
    GROUP BY city ORDER BY min(start_date) ASC");

Search()方法来处理自动完成搜索:

public function search(Request $request){
    $search = $request->term;
    $conferences = Conference::where('name', 'LIKE', '%'.$search.'%')->get();

    //$cities = Conference::where('city', 'LIKE', '%'.$search.'%')->distinct()->get(['city']);
    $cities = DB::raw("SELECT city, min(start_date) FROM conferences WHERE city LIKE '%" . $search . "%'
     GROUP BY city ORDER BY min(start_date) ASC");
    $data= [];
    foreach ($conferences as $key => $value){
        $data[] = ['category'=> 'Conferences', 'value' => $value->name, 'url' => 'conference/'.$value->id.'/'.$value->slug];
    }
    foreach ($cities as $key => $value){
        $data[] = ['category'=> 'Cities', 'value' => $value->city, 'url' => 'conferences/where/city/'.$value->city];
    }
    return response($data);
}

返回“ $data”的$cities = Conference::where('city', 'LIKE', '%'.$search.'%')->distinct()->get(['city']);显示:

[{category: "Cities", value: "Newcastle", url: "conferences/where/city/Newcastle"}]
0
:
{category: "Cities", value: "Newcastle", url: "conferences/where/city/Newcastle"}

显示“ $cities = DB::raw("SELECT city, min(start_date) FROM conferences WHERE city LIKE '%" . $search . "%' GROUP BY city ORDER BY min(start_date) ASC");

[]
No properties

0 个答案:

没有答案