Laravel SQL 条件查询

Laravel SQL query on condition

假设我有如下函数(在 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 查询构建期间执行条件操作?

谢谢

您可以将函数更改为:

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();    
}

请试一试,这应该有效:

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;

}