【问题标题】:Laravel conditions in Controller where clauseController where 子句中的 Laravel 条件
【发布时间】:2014-06-30 17:28:01
【问题描述】:

我正在尝试基于 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 if-statement laravel conditional-statements clause


    【解决方案1】:

    您缺少变量,不是吗?您还没有告诉 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();
    

    【讨论】:

    • 非常感谢 Unnawut
    • 在获得更多反对票之前,您可能仍想完善您的问题。尝试添加您第一次尝试时收到的错误消息可能会有所帮助。
    • 我尝试了您的帮助并显示此 POST localhost/adpanel/public/getDataordenes/… 500 (Internal Server Error)
    • 向我们展示您来自app/storage/logs/laravel.log的最后一条错误消息
    • 啊,我的回答漏掉了一个分号,现在更正了。我希望你发现了这一点。
    猜你喜欢
    • 2019-11-03
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多