ctr*_* f5 0 php mysql laravel laravel-5
如何创建这样的查询?
SELECT id,name,if(id > 17,'yes','no')as present FROM `ref`;
Run Code Online (Sandbox Code Playgroud)
在 Laravel 中有多种方法可以实现这一目标。您可以选择使用查询构建器路线或雄辩路线
使用查询生成器,它会像这样
DB::table('ref')->select(['id','name',DB::raw('(case when (id > 17) then "yes" else "no" end) as present')])->get();
Run Code Online (Sandbox Code Playgroud)
通过 Eloquent,您可以选择使用 Accessor 和 Mutators 或在选择查询中添加 DB::raw
使用Mutators和Accessors,您首先将新的标头/属性附加到您的属性中,如下所示
protected $appends = ['present'];
Run Code Online (Sandbox Code Playgroud)
然后您为新标题/属性编写条件。
public function getPresentAttribute(){
if($this->attributes['id'] > 17)
return $this->attributes['present'] = "yes";
return $this->attributes['present'] = "no";
}
Run Code Online (Sandbox Code Playgroud)
每当您查询参考模型时,当前属性都会添加到您的查询结果中,根据您的条件,其值为“是”或“否”。
你也可以选择在你的 Eloquent 中使用DB::raw从而放弃访问器/修改器路线
App\Ref::select(['id','name',DB::raw('(case when (id > 17) then "yes" else "no" end) as present')])->get();
Run Code Online (Sandbox Code Playgroud)