假设我有一个像波纹管一样的功能(在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中执行有条件的事情?
由于
答案 0 :(得分:1)
您可以将功能更改为:
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();
}
答案 1 :(得分: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;
}