【问题标题】:Laravel SQL query on conditionLaravel SQL 查询条件
【发布时间】:2015-05-01 18:02:28
【问题描述】:

假设我有如下功能(在 Laravel 4.2 中):

public static function getResult($class_id,$section_id,$session,$term,$setTerm = ture)
{
     $result = self::with('Student','Student.getClass','Student.getSection')
        ->where('class_id',$class_id)
        ->where('section_id',$section_id)
        ->where('exam_year',$session)
        ->where('term',$term)
        ->orderBy('class_roll','ASC')->get();

    return $result;

}

因此,如果 $setTerm 设置为 false,则不应执行 (->where('term',$term))

在查询构建期间如何在 Laravel 中执行条件操作?

谢谢

【问题讨论】:

    标签: php mysql laravel laravel-4 laravel-5


    【解决方案1】:

    请尝试一下,这应该可以:

    public static function getResult($class_id,$section_id,$session,$term,$setTerm = ture)
    {
         $result = self::with('Student','Student.getClass','Student.getSection')
            ->where('class_id',$class_id)
            ->where('section_id',$section_id)
            ->where('exam_year',$session);
    
         if($setTerm){ 
            $result->where('term',$term);
         }
    
         $result->orderBy('class_roll','ASC')->get();
    
         return $result;
    
    }
    

    【讨论】:

      【解决方案2】:

      你可以把函数改成这样:

      public static function getResult($class_id,$section_id,$session,$term,$setTerm = true)
      {
           $query = self::with('Student','Student.getClass','Student.getSection')
              ->where('class_id',$class_id)
              ->where('section_id',$section_id)
              ->where('exam_year',$session);
      
          if ($setTerm) {
              $query->where('term',$term);
          }
      
          return $query->orderBy('class_roll','ASC')->get();    
      }
      

      【讨论】:

      • 一个小瑕疵,你得把get()的返回值赋值给$query或者直接返回。否则getResult() 将返回一个查询构建器实例,而不是实际结果。
      猜你喜欢
      • 2020-10-24
      • 2020-10-11
      • 2020-09-19
      • 2016-11-06
      • 2011-07-01
      • 1970-01-01
      • 2021-09-18
      • 2014-10-04
      • 2018-06-27
      相关资源
      最近更新 更多