如何在 eloquent (laravel 4) 中使用 substr 进行查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16626702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:47:40  来源:igfitidea点击:

how to make query with substr in eloquent (laravel 4)?

laravellaravel-4substreloquent

提问by Carlos Su?ol

I have this query:

我有这个查询:

select substr(id,1,4) as id
from meteo.a2012
group by substr(id,1,4)

I just want to take first 4 numbers to my id row, but I'm trying to do in eloquent, how I do?

我只想把前 4 个数字带到我的 id 行,但我想用雄辩的方式做,我该怎么做?

Thanks.

谢谢。

回答by Jason Lewis

You need to use raw expressionsso you can use special functions like that.

您需要使用原始表达式,以便可以使用这样的特殊函数。

Model::select(DB::raw('substr(id, 1, 4) as id'))->groupBy(DB::raw('substr(id, 1, 4)'))->get();

Where Modelis your Eloquent model you want to run the query on.

Model你想运行查询的 Eloquent 模型在哪里。

回答by BCPNAYAK

$ids = Model::get(['id']);
foreach ($ids as $str)
{
    $str->id =substr($str->id,1,4);
}
return $ids;