如何创建这样的查询?
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 Model,present属性都将添加到查询结果中,其值为yes或no(取决于您的条件)。
您还可以选择在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中没有等效语句。