【发布时间】:2017-10-17 04:00:22
【问题描述】:
Hello Stack 溢出社区
我目前有以下代码(示例 1),它将使用附加连接返回带有食物类型和区域的餐厅列表。
我需要添加更多的 WHERE 子句,但前提是有任何要传递的子句,例如 (example 2)
搜索可能只有名称或名称的一部分,也许他们只是想按地区或食物类型进行搜索。
示例 1
$q = Input::get ( 'q' );
if($q != ""){
$restaurants = DB::table('restaurant')
->where ( 'restaurant.name', 'LIKE', '%' . $q . '%' )
->join ( 'area', 'restaurant.area_id', '=', 'area.id' )
->join ( 'food_type', 'restaurant.food_type_id', '=', 'food_type.id' )
->select( 'restaurant.*', 'food_type.name as food_type_name', 'area.slug as area_slug', 'area.name as area_name')
->paginate(2);
$pagination = $restaurants->appends ( array (
'q' => Input::get ( 'q' )
) );
} else {
$restaurants = DB::table('restaurant')
->join ( 'area', 'restaurant.area_id', '=', 'area.id' )
->join ( 'food_type', 'restaurant.food_type_id', '=', 'food_type.id' )
->select( 'restaurant.*', 'food_type.name as food_type_name', 'area.slug as area_slug', 'area.name as area_name')
->paginate(15);
}
示例 2
if ($q){
->where ( 'restaurant.name', 'LIKE', '%' . $q . '%' )
}
if ($request->has('area')){
->where('area', $request->input('area'));
}
if ($request->has('foodtype')){
foreach(foodtype as name => value)
->where('foodtype', $value);
}
我觉得应该有办法做到这一点,而不是为每个可能的结果写出不同的查询
我已经测试了 Unamata Sanatarai 的响应,(示例 3 但这有一个错误:
调用未定义的方法 Illuminate\Database\Query\Builder::appends()
我尝试将 ->paginate() 替换为 ->get()(如另一篇文章中所述),但我收到相同的错误
示例 3
$q = Input::get ( 'q' );
if($q != ""){
$restaurants = DB::table('restaurant');
$restaurants->where ( 'restaurant.name', 'LIKE', '%' . $q . '%' );
$restaurants->join ( 'area', 'restaurant.area_id', '=', 'area.id' );
$restaurants->join ( 'food_type', 'restaurant.food_type_id', '=', 'food_type.id' );
$restaurants->select( 'restaurant.*', 'food_type.name as food_type_name', 'area.slug as area_slug', 'area.name as area_name');
$restaurants->paginate(15);
$pagination = $restaurants->appends ( array (
'q' => Input::get ( 'q' )
) );
} else {
$restaurants = DB::table('restaurant')
->join ( 'area', 'restaurant.area_id', '=', 'area.id' )
->join ( 'food_type', 'restaurant.food_type_id', '=', 'food_type.id' )
->select( 'restaurant.*', 'food_type.name as food_type_name', 'area.slug as area_slug', 'area.name as area_name')
->paginate(15);
}
示例 4 将解释我最近的错误
未定义属性:Illuminate\Database\MySqlConnection::$main_image
$main_image 是数据库中的字段之一 - 在我将查询更改为示例 3 之前,它运行良好
示例 4 显示带有链接的新代码,这会产生错误
示例 4
$restaurants = DB::table('restaurant');
$restaurants->join ( 'area', 'restaurant.area_id', '=', 'area.id' );
$restaurants->join ( 'food_type', 'restaurant.food_type_id', '=', 'food_type.id' );
$restaurants->select( 'restaurant.*', 'food_type.name as food_type_name', 'area.slug as area_slug', 'area.name as area_name');
$restaurants->paginate(15)->links();
【问题讨论】:
-
通过您的编辑,您提出了不同的问题。
标签: php laravel-5.5