我在Laravel的where
语句中遇到了问题。我使用它从数据库中获取数据,然后将其推送到实时搜索:
$launchsitesatellite = DB::table('satellites')
->orWhere('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')
我需要添加它来过滤来自数据库的结果:->where('site', $site_code)
。
我尝试将其添加到上面的where
语句中,但是当我尝试在输入中输入内容时,它突破了我的实时搜索并导致500服务器错误。我可以使用->where('site', $site_code)
来显示数据库中的数据,但不能搜索它。
我的问题是:为什么->where('site', $site_code)
查询会破坏搜索以及如何解决?
编辑: 我的控制器代码段:
if ($request->ajax())
{
$output="";
$launchsitesatellite = DB::table('satellites')
->orWhere('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')
if ($launchsitesatellite)
{
foreach ($launchsitesatellite as $key => $launchsitesatellites) {
$output .='<tr>'.
'<td>'.$launchsitesatellites->satname.'</td>'.
'<td>'.$launchsitesatellites->norad_cat_id.'</td>'.
'<td>'.$launchsitesatellites->object_type.'</td>'.
'</tr>';
}
}
return $output;
}
else {
$launchsitesatellite = DB::table('satellites')->where('site', $site_code)->get();
return view('pages/launchsite-filter', compact('launchsites', 'launchsitesatellite'));
}
}
&#13;
答案 0 :(得分:2)
您必须隔离or
语句。试试这个:
$launchsitesatellite = DB::table('satellites')
->where(function($q) use ($request) {
$q->orWhere('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%');
})
->where('site', $site_code)->get();
答案 1 :(得分:2)
让我们来看看if-block中的代码:
if ($request->ajax())
{
$output="";
$launchsitesatellite = DB::table('satellites')
->orWhere('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')
if ($launchsitesatellite)
{
foreach ($launchsitesatellite as $key => $launchsitesatellites) {
$output .='<tr>'.
'<td>'.$launchsitesatellites->satname.'</td>'.
'<td>'.$launchsitesatellites->norad_cat_id.'</td>'.
'<td>'.$launchsitesatellites->object_type.'</td>'.
'</tr>';
}
}
return $output;
}
您收到的错误(提到here)是
Undefined property: Illuminate\Database\MySqlConnection::$satname
当你定义$launchsitesatellite
时,你将where子句添加到SQL语句中,但永远不会启动它。
相反,这样做:
$launchsitesatellite = DB::table('satellites')
->orWhere('satname', 'LIKE', '%' . $request->search . '%')
->orWhere('norad_cat_id', 'LIKE', '%' . $request->search . '%')
->get();