Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 215
Carlos Suñol Avatar asked May 18 '13 16:05

Carlos Suñol


People also ask

What is use of query () in Laravel?

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.

What is Laravel eloquent query?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

What is the difference between eloquent and query builder in Laravel?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.


1 Answers

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.

like image 111
Jason Lewis Avatar answered Sep 20 '22 12:09

Jason Lewis