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

Carlos Suñol picture Carlos Suñol · May 18, 2013 · Viewed 7.9k times · Source

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?

Thanks.

Answer

Jason Lewis picture Jason Lewis · May 19, 2013

You need to use raw expressions so 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 Model is your Eloquent model you want to run the query on.