php - 为什么具有 distinct 和 group by 的查询不返回结果?
问题描述
我有这个查询来获取“城市”列等于 $search 的会议。
$cities = Conference::
where('city', 'LIKE', '%'.$search.'%')
-> distinct()->get(['city']);
但我还想按会议“开始日期”列的结果排序。但这样是行不通的:
$cities = Conference::
where('city', 'LIKE', '%'.$search.'%')
->distinct()->orderBy('start_date', 'asc')
->get(['city','start_date']);
例如,如果用户在搜索自动完成字段中引入“New”,则 distinct 不起作用,它会出现多次,例如“Newcastle”,而不是只出现一次。
你知道为什么吗?
也像这样,使用 group by,当用户引入例如“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
解决方案
推荐阅读
- java - 更改变量时重绘不起作用
- c# - 我不知道为什么,但我的附加力不起作用我有一个刚体 2d,代码看起来正确但它仍然不起作用?
- angular - 从 Observable Array of Objects 迭代 *ngFor 时如何修复 InvalidPipeArgument 错误
- javascript - 如何使用 JavaScript 语言在 Jmeter WebDriver Sampler 中设置 InternetExplorerOptions?
- apache - mod_jk 使用 Lucee 和 Apache 生成不正确的重定向查询字符串
- system-verilog - DPI-C 中 Struct 中的动态数组
- node.js - 使用 Node.js 从 txt 文件中读取坐标
- android - com.google.android.gms.internal.firebase-perf.zza 中缺少方法
- python - 当用户选择年级时,Django用正确的科目更新显示的内容
- angular - 调用 API 服务后 Angular 丢失值列表