如何在laravel中创建带有IF(表达式,value_IF_true,value_IF _ffalse)的条件查询


How to create conditional query with IF(expression, value_if_true,value_if_false) in laravel?

如何创建这样的查询?

SELECT id,name,if(id > 17,'yes','no')as present FROM `ref`;

在Laravel中有几种方法可以实现这一点。您可以选择使用查询生成器路线或Eloquent路线

有了查询生成器,它将像这样运行

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

使用Eloquent,您可以选择使用Accessor和Mutators,或者在选择查询中添加DB::raw

对于突变体和访问器,您首先将新的头/属性附加到您的属性上,就像一样

protected $appends = ['present'];

然后为新的头/属性编写条件。

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

使用此功能,无论何时查询Ref Modelpresent属性都将添加到查询结果中,其值为yesno(取决于您的条件)。

您还可以选择在Eloquent中使用DB::raw,从而放弃访问器/变异器路由

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

这可以通过CASE语句来完成

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

在Laravel中使用Raw()SQL语句,在Eloquent中没有等效语句。