Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DATEDIFF function with Eloquent?

Here is my code for selecting reservations:

Reservation::select(array(
    'obj_id', 
    'name', 
    'surname',
    'date_from',
    'date_to', 
    'days',
    'status',
    'slug',
    'payable'
));

My question is how to change 'days' to get real diff between date_from and date_to? I don't have 'days' column in the database, I just want to count them in the SQL query.

In pure SQL should be something like that:

SELECT DATEDIFF('date_from, date_to) AS Days FROM RESERVATIONS;

How can I do that using Eloquent?

like image 372
Maciej Płocki Avatar asked Aug 06 '13 10:08

Maciej Płocki


1 Answers

You can use DB::raw for this.

Reservation::select(array(
            'obj_id', 'name', 'surname',
            'date_from', 'date_to', 
            'days',
            'status', 'slug', 'payable', 
            DB::raw("DATEDIFF(date_from,date_to)AS Days"))
))
like image 200
Abishek Avatar answered Oct 05 '22 21:10

Abishek