簡體   English   中英

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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM