2016-04-29 34 views

回答

3

有幾種方法可以在Laravel中實現此目的。你可以選擇去與查詢生成器路由或能言善辯的路線

隨着查詢生成器會去這樣

DB::table('ref')->select(['id','name',DB::raw('(case when (id > 17) then "yes" else "no" end) as present')])->get(); 

並與雄辯,你可以選擇使用存取和修改器或添加DB ::生在您選擇查詢

與變異符和訪問器,你先把你新的頭/屬性附加到你的屬性,像這樣

protected $appends = ['present']; 

那麼你就寫你的康迪特你的新頭/屬性。

public function getPresentAttribute(){ 

    if($this->attributes['id'] > 17) 
     return $this->attributes['present'] = "yes"; 
    return $this->attributes['present'] = "no"; 

} 

有了這個任何時候你查詢參考模型目前屬性將被添加到您的查詢結果與根據您的病情一的沒有值。

你也可以選擇使用DB ::原料在你的雄辯也因此放棄了訪問/突變路線

App\Ref::select(['id','name',DB::raw('(case when (id > 17) then "yes" else "no" end) as present')])->get(); 
0

這可以用CASE聲明

SELECT CASE WHEN <test>  THEN <returnvalue> 
      WHEN <othertest> THEN <returnthis> 
          ELSE <returndefaultcase> 
     END AS <newcolumnname> 
FROM <table> 

完成在Laravel使用Raw() SQL語句中有口才沒有等價。