我正在尝试根据网址参数构建查询。加载Controller时,我需要检查已提供的参数并从中构建查询。它使用静态值,但不使用条件语句。我的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;
};
}
}
答案 0 :(得分:3)
你错过了变量,不是吗?你没有告诉PHP在你的情况下做where()
的变量/对象是什么。 Laravel的Eloquent(以及许多其他库)的神奇之处在于,当你调用它的方法时,它会返回它自己(对象),所以你可以立即调用另一个方法。
所以当你这样做时:
$data = DB::table("ordens")
->select(...)
->where(...);
与:
相同$data = DB::table("ordens");
$data = $data->select(...);
$data = $data->where(...);
但是您在->where(...)
条件之后立即尝试if
。您需要告诉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();