控制器where子句中的Laravel条件


Laravel conditions in Controller where clause

我试图建立一个基于URL参数的查询。当控制器加载时,我需要检查已提供哪些参数并从中构建查询。它可以处理静态值,但不能处理条件语句。我的laravel语法正确吗?

class OrdenesController extends BaseController {
public function showOrdenes($action)
{
  $my_id = Auth::user()->id;
  $my_cod = Auth::user()->codprov;
  switch ($action) 
  {
    case 'list':
      $rows = DB::table('ordens')->count();
      if(Input::get("jtSorting"))
      {
       $search = explode(" ", Input::get("jtSorting"));            
       $numorden= Input::get("nro_orden");
       $filtros =explode(" ", $filtros);
       $data = DB::table("ordens")
        ->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
        ->where('cod_prov', '=', $my_cod)
        ->where('nro_orden', '=', $numorden)///work
        ---------- ////no work
        if (Input::has('nro_orden')) {
           ->where('nro_orden', '=', $numorden)
        }
        ---------- /// no work
        ->groupBy('nro_orden')
        ->skip(Input::get("jtStartIndex"))
        ->take(Input::get("jtPageSize"))
        ->orderBy($search[0], $search[1])
        ->get();
      }
      return Response::json(
        array(
          "Result"      =>    "OK",
          "TotalRecordCount"  =>    $rows,
          "Records"     =>    $data
        )
      );
      break;
   };  
  }    
}

你错过了变量,不是吗?您还没有告诉PHP在您的条件中对哪个变量/对象执行where()。Laravel的Eloquent(以及许多其他库)的神奇之处在于,当你调用它的方法时,它会返回自己(对象),这样你就可以立即对它进行另一个方法调用。

所以当你这样做的时候:

$data = DB::table("ordens")
    ->select(...)
    ->where(...);

等于:

$data = DB::table("ordens");
$data = $data->select(...);
$data = $data->where(...);

但是你试图在if条件之后立即做->where(...)。您需要告诉PHP您试图从哪个对象/变量调用该方法。这样的:

$num = Input::get("nro_orden");
$data = DB::table("ordens")
    ->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
    ->where('cod_prov', '=', $my_cod);
if (Input::has('nro_orden')) {
    $data = $data->where('nro_orden', '=', $num);
}
$data = $data->groupBy('nro_orden')
    ->skip(Input::get("jtStartIndex"))
    ->take(Input::get("jtPageSize"))
    ->orderBy($search[0], $search[1])
    ->get();